Why does Ajax form submit twice? - javascript

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.

Related

Trying to stop form from redirecting after submit (return false & prevent.default are not working!)

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"/>

how to get ajax response to trigger click

I have two forms for buy now and for pincode when I click buynow button sending request through ajax and same thing is done for pincode form also.
HTML
<form method="POST" action="/cart/add" id="myForm">
.....
....
<input type="button" class="buyNowBtn" id="btnBuyNow"/>
</form>
<form action="#">
<input type="text" id="pinCheck" class="pinCheck" placeholder="enter pin code" />
<button class="btn btn-info" id="pinCheckTest"> Check</button>
</form>
In the same buynow click event I need to trigger a pincode submit button, so I did this
(document).on('click', '#btnBuyNow', function (e) {
....
....
$("#pinCheckTest").trigger('click');
....
});
the above trigger event is successfully calling pincode click event
$('#pinCheckTest').click(function () {
$.ajax({
type: 'GET',
url: url,
success: function (output) {
if (output == 'true') {
}
else{
}
}
});
but I need to get ajax response back to trigger event so that I can do some operation is it possible?
something like
(document).on('click', '#btnBuyNow', function (e) {
....
....
$var output=$("#pinCheckTest").trigger('click');//I need to get ajax response back to this click
if(output=='true'){
......
}else{
.....
}
....
});
You can define a variable outside of both click handlers, when .trigger() is called, assign $.ajax() to variable, use .then() within first click handler to process results of $.ajax() call.
Note, included event.preventDefault() to prevent submission of <form>, as pointed out by #IsmailRBOUH
var dfd;
$(document).on('click', '#btnBuyNow', function (e) {
e.preventDefault();
....
....
$("#pinCheckTest").trigger('click');
if (dfd) {
dfd.then(function(output) {
// do stuff with output
console.log(output)
})
}
....
});
$('#pinCheckTest').click(function (e) {
e.preventDefault();
dfd = $.ajax({
type: 'GET',
url: url,
success: function (output) {
if (output == 'true') {}
else{};
}
})
});
var dfd;
$("#first").click(function() {
$("#second").trigger("click");
if (dfd) {
dfd.then(function(data) {
alert(data)
})
}
})
$("#second").click(function() {
// do ajax stuff
dfd = $.when("second clicked")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="first">first button</button>
<button id="second">second button</button>
Since you are binding the click event to a button inside form you have the prevent the default behaviour which is 'submit the form'. Change you code to :
$('#pinCheckTest').click(function (e) {
e.preventDefault();
//Your ajax call
});
Here is a demo to clarify the difference https://jsfiddle.net/qvjjo3jk/.
Update1:
Add an id to your form:
<form action="#" id="pinCheckForm">
<input type="text" id="pinCheck" class="pinCheck" placeholder="enter pin code" />
<button class="btn btn-info" id="pinCheckTest"> Check</button>
</form>
Then:
$('#pinCheckForm').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: url,
data: $(this).serialize(), //Sends all form data
success: function(output) {
if (output == 'true') {} else {}
}
});
});

How to clear all inputs after form submission

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/

Submit form when enter key is pressed

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....

how can i know the cursor is now focus in input or textarea or select

I want to run ajax to get a value , if value is true ,then submit the form, the code bellow using onsubmit=xxx , but this form will submit immediately , not waiting ajax result. then I want to using an "a" tag with onclick function to submit the form , this can do the job, but when I using "enter" key to submit the form , will not run ajax codes. then I want to bind keypress when the cursor is in input field to submit the form. how to check the cursor is in or out of the form fields?
<?php
if(isset($_POST['act'])){
$rs=array(
'status'=>0
);
echo json_encode($rs);
exit;
}
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<div class="filters">
<form onsubmit="return filters.submit()">
<input type="text" name="name" />
<input type="submit" value="submit" />
</form>
</div>
<script type="text/javascript">
var filters={
form: $('.filters').find('form'),
submit: function (){
$.ajax({
url:'index.php',
type:'POST',
data:{
act:'ajax'
},
success:function(rs){
eval('var rs='+rs);
if(rs['status']==1){
return true;
}else{
return false;
}
}
});
}
}
</script>
As #Rajesh Jinaga said document.activeElement return the currently focused element but I want to explain you why it doesn't work.
When you are making your ajax call it won't wait until the ajax return true or false. It will execute. So you need to prevent the form to be submited and submit it with javascript when your ajax call is finished.
HTML
<form>
<input type="text" name="name" />
<input type="submit" value="submit" />
</form>
JAVASCRIPT (jQuery)
$('form').submit(function (e){
$.ajax({
url:'index.php',
type:'POST',
data:{
act:'ajax'
},
success:function(rs){
// No need of EVIL eval('var rs='+rs);
if(rs['status']==1){
$(this).submit(); // Will submit the form.
}else{
alert("FAILED!");
}
}
return false; // Shortcut for e.preventDefault() and e.stopPropagation() so it will prevent the form to be submitted.
});
document.activeElement returns the currently focused element, that is, the element that will get keystroke events if the user types any.
$(this).submit() won't work because you are in different context, and success callback invoker send ajax related object but not form DOM object. Store object into a variable in the form context and use it in success callback.
$(function(){
$('form').submit(function (){
var form = this;
$.ajax({
url:'index.php',
type:'POST',
data:{
act:'ajax',
status: $('[name=status]').val()
},
success:function(rs){
eval('var rs='+rs);
if(rs['status']==1){
$(form).submit(); // or $('form').submit()
}else{
alert('error');
}
}
});
return false;
});
});
#L105, thank you for your answer, I modify my code to match your answer , but the form can not submit using $(this).submit();
<?php
if(isset($_POST['act'])){
$rs=array(
'status'=> $_POST['status']
);
echo json_encode($rs);
exit;
}
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<div class="filters">
<form action="index.php" method="post">
<input type="text" name="status" />
<input type="submit" value="submit" />
</form>
</div>
<script type="text/javascript">
$(function(){
$('form').submit(function (){
$.ajax({
url:'index.php',
type:'POST',
data:{
act:'ajax',
status: $('[name=status]').val()
},
success:function(rs){
eval('var rs='+rs);
if(rs['status']==1){
$(this).submit(); // can't submit
}else{
alert('error');
}
}
});
return false;
});
});
</script>

Categories