I currently have a live chat room up and running and just asked some users what I can do to make the chat room even better. One thing that was asked multiple times was this...
"Can you please add a feature where pressing the enter button will send my message instead of adding a new line in the text box?"
I tried to apply some jQuery from a different post on StackOverflow but couldn't get it to work. Here is my current code...
jQuery:
<!-- jQuery for submitting form -->
<script>
var msgForm = false;
$(function () {
$('.expand').keyup(function(event) {
if (event.keyCode == 13) {
this.form.submit();
msgForm = true;
return true;
}
});
if( msgForm = true ) {
$('#formSend').on('submit', function (e) {
e.preventDefault();
var formData = $('form').serialize();
$('.expand').prop("disabled", true)
$.ajax({
type: 'post',
url: 'send.php',
data: formData,
success: function () {
$(".expand").val('');
$('.expand').prop("disabled", false)
}
});
});
}
});
</script>
Here ^^ an Ajax request is made to send the message so no page refresh is involved like a usual form.
Here is the HTML markup for the form if needed...
<form action="send.php" method="post" name="formSend" id="formSend" />
<textarea id="styled" class="expand" name="msg" placeholder="Your Message Here" onfocus:"setbg(\'#e5fff3\');"required></textarea>
<input type="submit" name="submit" value="Send" class="send" />
</form>
I just tested this in a jsfiddle and it works fine.
html:
<form>
<textarea></textarea>
<input type="submit" value="Submit"/>
</form>
javascript:
$("textarea").keyup(function(event){
if(event.keyCode == 13){
$("form").submit();
}
});
$("form").on('submit', function(e){
e.preventDefault();
alert('abcde');
});
Demo
Why not just put them in one action. No need to separate. Like this:
<form action="send.php" method="post" name="formSend" id="formSend" />
<textarea id="styled" class="expand" name="msg" placeholder="Your Message Here" onfocus:"setbg(\'#e5fff3\');" required></textarea> <br/>
<input type="submit" name="submit" value="Send" class="send" />
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.expand').keyup(function(event) {
if(event.keyCode == 13) {
var formData = $('#formSend').serialize();
$(this).prop('disabled', true);
console.log(formData);
$.ajax({
type: 'POST',
url: 'send.php',
// url: document.URL,
data: formData,
success: function(response) {
$('.expand').attr('placeholder', 'Sending Message...');
setTimeout(function(){
$('.expand').attr('placeholder', 'Your Message Here').prop('disabled', false);
// sample delay
}, 1000);
$(".expand").val('');
}
});
}
});
});
</script>
Why not trigger an event click if the user press the enter key
$('selector').on('keyup', function(e) {
if(e.which == 13) {
$('button_selector').trigger('click');
}
}
$('button_selector').on('click', function() {
//do ajax request here.....
});
// get from my code hope it hepls....
Related
The problem I've been trying to solve for hours and hours now is following: I cannot stop the redirecting of #myform action after the data has been submitted succesfully to database. I've tried multiple methods but none seem to work. I'm in dire need of help!
The code:
Html(mainview.php):
<div id="submitAccordion">
<form id="myForm" action="userFiles.php" method="post">
Name: <input type="text" name="accordionName" /><br />
<input id="sub" type="submit" name="go" />
</form>
<span id="result"> </span>
</div>
Javascript(mainview_script.js):
$("#sub").click(function () {
var data = $("#myForm :input").serializeArray();
$.post( $("#myForm").attr("action"),
data, function(info) {
$("#result").html(info); } )
});
$("#myForm").submit(function () {
return false;
});
php(userFiles.php):
session_start();
require_once 'database.php';
if ( isset($_SESSION['user_id']) ) {
$sql = "INSERT INTO useraccordion (id, h3) VALUES (:id, :accordion)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':id', $_SESSION['user_id']);
$stmt->bindParam(':accordion', $_POST['accordionName']);
if ( $stmt->execute() ) {
echo "Succesfully inserted";
} else {
echo "Sorry, there was an error";
}
}
I have tried ajax method, prevent.default etc, but none work!
Either change your input type to button
<input id="sub" type="button" name="go" value="Submit"/>
Or try this:
$("form").submit(function(e){
e.preventDefault();
});
First, move your $("#myForm").submit(... out of the click event so it is it's own thing. Then, pass in e into that function. So it would look like this...
$("#myForm").submit(function(e) {
e.preventDefault();
return false;
});
$("#sub").click(function() {
var data = $("#myForm :input").serializeArray();
$.post( $("#myForm").attr("action"),data, function(info) {
$("#result").html(info);
});
});
That will fix your immediate problem. My thought is... Do not even use a form for this. There is no reason to. You are posting the data via Ajax, so there is no reason to have a form that would submit. I would do something like this...
HTML...
<div id="form">
<div class="form-item">
<label for="name">Name:</label>
<input name="name" id="name" type="text" />
</div>
<button id="sub">Submit Form</button>
</div>
Javascript...
$("#sub").click(function() {
var postData = {};
//this is here to be dynamic incase you want to add more items....
$("#form").find('input').each(function() {
postData[$(this).attr('name')] = $(this).val();
});
$.ajax({
url: "YOUR URL HERE",
type: "POST",
data: postData,
success: function(msg) {
$("#result").html(msg);
}
});
});
It is sufficient to prevent deafult action on sub:
$("#sub").click(function (e) {
e.preventDefault();
var data = $("#myForm :input").serializeArray();
$.post( $("#myForm").attr("action"),
data, function(info) {
$("#result").html(info); } )
});
$("#myForm").submit(function (event) { event.preventDefault(); });
That should stop the submission
If you are submitting your form data via ajax or jquery then you should change your input type form 'submit' to 'button' type
<input id="sub" type="button" name="go" value="go"/>
With Ajax and JS/Jquery I'm trying to send a simple Contact form to a Classic ASP (aspemail) and sent a messagem from a page without reload.
<form id="form-submit" action="ASPEmail.asp" method="post">
Name<br>
<input id="name" type="text"><br>
E-mail<br>
<input id="email" type="text"><br>
Message:<br>
<textarea id="msg"></textarea><br>
<input type="submit" id="btn" value="SEND">
<img src="loading.gif" class="loading">
</form>
My ASPEMAIL.ASP is only test asp and I write only:
<%
Response.Write("ok")
%>
And my JQuery Script:
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script>
$(function() {
$("#form-submit").submit(function() {
var data = $(this).serialize(),
action = $(this).attr("action"),
method = $(this).attr("method");
$(".loading").show(); // show loading div
$.ajax({
url: action,
type: method,
data: data,
success: function(data) {
if(data === "ok")
{
document.location = "final.asp";
}
},
error: function(err) {
// there was something not right...
},
complete: function() {
$(".loading").hide(); // hide the loading
}
});
return false; // don't let the form be submitted
});
});
</script>
I put a redirect on success to test (My objective is a message only) - but nothing happens.
But after send the "LOADING" appears on screen and hide and then the submit and "complete" is working.
Any idea what is wrong?
you have 2 variables named data, try using a different variable here, as I believe you're "confusing" javascript here :)
success: function(dataReturned) {
if(dataReturned === "ok")
{
document.location = "final.asp";
}
},
Why does the below script cause the form to submit twice? I can't figure this out, even after trying other solutions posted around the internet. Submitting twice is causing duplicate entries in the database. Thank you in advance for looking into this!
<script type="text/javascript">
$(document).ready(function(){
$('#form-error').hide();
$("#form-submit").click(function(){
$("#form").submit();
});
});
$('#form').submit(function(e) {
register();
e.preventDefault();
});
function register()
{
jQuery.ajax({
method: 'POST',
url: 'actions/add.php',
data: $('#form').serialize(),
dataType:'json',
success: function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
error(1,msg.txt);
}
}
});
}
function hideshow(el,act)
{
if(act)
{
$('#'+el).hide(0).slideDown(500, 'linear');
}
else $('#'+el).hide();
}
function error(act,txt)
{
if(txt)
{
$('#form-error').html(txt);
}
$('#form-error').hide(0).slideDown(500, 'linear');
}
</script>
HTML Form:
<form id="form">
<p>First Name:</p>
<input type="text" name="firstname" />
<p>Last Name:</p>
<input type="text" name="lastname" />
<p>E-Mail Address:</p>
<input type="text" name="emailaddress" />
<p>Sequence Assignment:</p>
<select name="sequence">
<option value="1">Default Sequence</option>
</select>
<button id="form-submit">Add User</button>
<p id="form-error"></p>
</form>
There are duplicated event listeners for the submit event:
1. When submit button clicked:
$("#form-submit").click(function(){
$("#form").submit();
});
2. When form is submitted:
$('#form').submit(function(e) {
register();
e.preventDefault();
});
You need only one of them.
Change your code like:
<script type="text/javascript">
$(document).ready(function(){
$('#form-error').hide();
$('#form').submit(function(e) {
register();
e.preventDefault();
});
});
function register()
{
.
.
.
I had a similar issue to this. If you just single click on the button does it enter duplicate data?
The way I got around it is once the click happened I disabled the button until after the Ajax call.
function register()
{
//disable button
jQuery.ajax({
method: 'POST',
url: 'actions/add.php',
data: $('#form').serialize(),
dataType:'json',
success: function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
error(1,msg.txt);
}
}
});
//Enable Button
}
Another option would be to do some checks in the php code that submits it to the database to see if that data already exists.
I want to clear all inputs value whenever result succeed.
I have tried unbind from Jquery but doesn't get any result
so any suggestion would be great
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.1.min.js"></script>
</head>
<body>
<div id="Result"></div>
<form id="Form" action="File.php" autocomplete="off">
<input type="text" name="Name" />
<br/>
<input type="text" name="Pass" />
<br/>
<input type="button" id="Submit" value="Run Code" />
</form>
<script>
$(document).ready(function()
{
$("#Submit").click(function()
{
$("#Form").submit(function(e)
{
$.ajax(
{
url: $(this).attr("action"),
type: "POST",
data: $(this).serializeArray(),
success: function(data, textStatus, jqXHR)
{
$("#Result").html(data);
}
});
e.preventDefault();
});
$("#Form").submit();
});
});
</script>
</body>
</html>
please feel free to ask for more details
You can clear all inputs using
$("input[type='text']").val('');
You are binding an event handler inside another event handler. Each time the button is clicked, a new handler is attached to the form. So, after n number of clicks, you'll be sending n number of ajax requests, as you can see here
Ideally, your code should be
$(document).ready(function () {
$("#Submit").click(function () {
$("#Form").submit();
});
$("#Form").submit(function (e) {
e.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: "POST",
data: $(this).serializeArray(),
success: function (data, textStatus, jqXHR) {
$("input[type='text']").val(''); // reset the input values
$("#Result").html(data);
}
});
});
});
Demo.
Side note: You can simply use a submit button instead of triggering the form submission manually like this
Here you go:
$(document).find('input').each(function(){
$(this).val('');
});
More info on: http://api.jquery.com/val/
I want to call a function when I press enter in the input field. The problem is, that it just reloads the page at the moment, and doesn't call the JavaScript. The JavaScript works without any problems, when I'm pressin the button. Now I want to have the same result, when I press enter.
This is my form
<form onSubmit="changeView()">
<input type="text" value="London" name="region" id="region">
<input type="button" onClick="changeView()" name="mySubmit" value="Search" >
</form>
I also tried to put this into the text field onKeydown="Javascript: if (event.keyCode==13) changeView();
But it didn't really help.
This is my JavaScript function
function changeView(){
var region = document.getElementById('region').value;
$.ajax({
type: 'GET',
url: 'webservice.php',
data: {region: region},
success: function(response, textStatus, XMLHttpRequest) {
alert("SUCCESS");
map.panTo(new L.LatLng(response[0].lat,response[0].lon));
}
});
return false;
}
HTML:
<form action="webservice.php" method="post">
<input type="text" value="London" name="region" id="region">
<input type="submit" name="mySubmit" value="Search" >
</form>
Javascript:
$('#region').on('keydown', function(e) {
if (e.which === 13) {
$(this).parent('form').submit();
}
});
$('.form').on('submit', function(e) {
var self = $(this);
$.ajax({
type: self.attr('method') ,
url: self.attr('action'),
data: {region: $('#region').val()},
success: function(response, textStatus, XMLHttpRequest) {
alert("SUCCESS");
map.panTo(new L.LatLng(response[0].lat,response[0].lon));
}
});
e.PreventDefault();
return false;
});
it looks like you're using jQuery, have you thought about just biding an event to the text box
something like this
$(document).ready(function(){ // binds when the document has finished loading
$("#region").on('keypress', function(e){
if (e.which === 13){ // enter key
changeView();
}
});
});