Ajax Post Submit Function Submits Twice - javascript

I've tried many of the other solutions to this problem on SO, and elsewhere, but I can't seem to prevent my form from submitting twice. Here is the code that I'm currently having this issue with:
jQuery Code
$(function() {
var additemtoform = $('#additemform');
var handleData = function(responseData) {
if ($(responseData).find('#repitems').length) {
var replacement = $('<div />').html(responseData).find('#repitems').html();
$('#test').html(replacement);
} else {
additemtoform.submit();
}
};
$("#additemform .addbtn").on("click", function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'WebCatPageServer.exe',
dataType: 'html',
cache: false,
data: additemtoform.serialize(),
beforeSend: function() {},
success: function(data) {
handleData(data);
},
error: function() {
alert('error');
}
});
return false;
});
});
If I remove the submit in the callback, then the form doesn't submit at all. So, what am I missing?
Thanks!
Update
Note that this code is update from the original per Habbe's suggestion below. The same issue with the double submit persists, however.
HTML Code (Generated)
<form name="AddItem" id="additemform" method="post" action="WebCatPageServer.exe">
<input name="Action" type="hidden" value="Add_Item" />
<table>
<tbody>
<tr>
<td>BRW2394746301</td>
<td>239-47463-01</td>
<td>Gas Valve Complete, Icon Natural Gas</td>
<td> $207.32</td>
<td>Available</td>
<td>
<input name="Q1" tabindex="1" class="qtyfield" type="text" size="1" value="0" onblur="clickrecall(this,'0')" onfocus="Q1.select()" />
</td>
<td>
<input name="P1" type="hidden" value="BRW2394746301" />
<input name="M1" type="hidden" value="239-47463-01" />
<input name="D1" type="hidden" value="Gas Valve Complete, Icon Natural Gas" />
<button type="button" class="button lightgray smallrounded addbtn" value="Add">Add</button>
</td>
</tr>
<tr>
<td>BRW2394746501</td>
<td>239-47465-01</td>
<td>Gas Valve Complete , Icon Propane</td>
<td> $272.58</td>
<td>Available</td>
<td>
<input name="Q2" tabindex="2" class="qtyfield" type="text" size="1" value="0" onblur="clickrecall(this,'0')" onfocus="Q2.select()"/>
</td>
<td>
<input name="P2" type="hidden" value="BRW2394746501" />
<input name="M2" type="hidden" value="239-47465-01" />
<input name="D2" type="hidden" value="Gas Valve Complete , Icon Propane" />
<button type="button" class="button lightgray smallrounded addbtn" value="Add">Add</button>
</td>
</tr>
<tr>
<td>BRW2334784505</td>
<td>233-47845-05</td>
<td>Pilot Assembly, Icon Natural Gas</td>
<td> $32.58</td>
<td>Available</td>
<td>
<input name="Q3" tabindex="3" class="qtyfield" type="text" size="1" value="0" onblur="clickrecall(this,'0')" onfocus="Q3.select()" />
</td>
<td>
<input name="P3" type="hidden" value="BRW2334784505" />
<input name="M3" type="hidden" value="233-47845-05" />
<input name="D3" type="hidden" value="Pilot Assembly, Icon Natural Gas" />
<button type="button" class="button lightgray smallrounded addbtn" value="Add">Add</button>
</td>
</tr>
</tbody>
</table>
</form>
Solution - Final Code
As it turns out, I was overthinking this. The form was submitting via ajax on the initial submit. The form was submitted again in the callback. Since an item was added to the cart on the initial submit, I simply loaded the cart page in the callback.
$(function() {
var additemtoform = $('#additemform');
// Reset Qty to 0 on Page Load
$('#additemform .inputqty').val('0');
//Ajax CallBack
var handleData = function(responseData) {
if ($(responseData).find('#repitems').length) {
var replacement = $('<div />').html(responseData).find('#repitems').html();
$(replacement).appendTo('body').modal();
} else {
location.href = "WebCatPageServer.exe?Cart";
}
};
$("#additemform .addbtn").on("click", function(e) {
e.preventDefault();
// If qty is 0, set value to 1
if($(this).closest('tr').find('input[type=text]').val() === '0'){
$(this).closest('tr').find('input[type=text]').val('1');
}
else {
}
// Post Form
$.ajax({
type: 'POST',
url: 'WebCatPageServer.exe',
dataType: 'html',
cache: false,
data: additemtoform.serialize(),
beforeSend: function() {},
success: function(data) {
handleData(data);
},
error: function() {
alert('error');
}
});
return false;
});

NB! ensure that the binding occurs just once and that you don't have multiple submit elements in your form.
You could try to include the event.stopPropagation call. I dont see how this could effect anything, but perhaps worth a shot.
$(function() {
var additemtoform = $('#additemform');
var handleData = function(responseData) {
if ($(responseData).find('#repitems').length) {
var replacement = $('<div />').html(responseData).find('#repitems').html();
$('#test').html(replacement);
} else {
additemtoform.submit();
}
};
$("#additemform .addbtn").on("click", function(e) {
e.preventDefault();
e.stopPropagation();
$.ajax({
type: 'POST',
url: 'WebCatPageServer.exe',
dataType: 'html',
cache: false,
data: additemtoform.serialize(),
beforeSend: function() {},
success: function(data) {
handleData(data);
},
error: function() {
alert('error');
}
});
return false;
});
});

On the third line, the function(e) is open telling function handleData(responseData) to run oy omitting the closing }. Then in the ajax you tell function handleData(responseData) to run again.

Try This:
$(function() {
var additemtoform = $('#additemform');
$("#additemform .addbtn").off().on("click", function(e) {
///your code
});

My guess would be, because you are calling submit form action twice. Once in the form tag, and secondly in jquery. Try removing one and see what happens.

During first time ajax call, the form is not submitted. Just passes the call and receives response length 0 or null. So the else part demands form submission again. So try to submit the form before first call and make sure form submit target is self().
Good Luck!

Related

The jQuery ajax does not send more than two values to post url

I have the following code to send the data via Jquery AJAX and notice that I have three values that need to be sent to the receiving file(Addtocart.php).
The transmission and reception were good, but after a while I do not know why it no longer sends.. When one of the values is canceled and two remain, it sends.. but when three values are not sent.
ajax
<script >
$(document).ready(function() {
$("#add-to-card").click(function() {
var quantityq = $("#quantityq").val();
var user = $("#user").val();
var product__id = $("#product__id").val();
$.ajax({
url: 'Addtocart.php',
method: 'POST',
data: {
quantityq: quantityq,
user: user,
product__id: product__id
},
success: function(data) {
$('#result').html(data);
}
});
});
});
</script>
<input step="1" min="1" max="50" name="quantityq" id="quantityq" value="1" title="Qty" class="input-text qty text" size="4" type="number">
<input type="hidden" name="user" id="user" value="72663">
<input type="hidden" name="product__id" id="product__id" value="4">
</div>
<button type="submit" id="add-to-card" class="btn sqaure_bt fll display-f">send</button>
It is not clear what issue you are facing, as you didn't post an example that shows the issue clearly.
But Rather than binding to click event of the button, you should bind to submit event of the form. This way, client-side form validation will work correctly and your JS code will be a lot smaller.
<form id="myForm">
<input step="1" min="1" max="50" name="quantityq" id="quantityq" value="1" title="Qty" class="input-text qty text" size="4" type="number">
<input type="hidden" name="user" id="user" value="72663">
<input type="hidden" name="product__id" id="product__id" value="4">
<button type="submit" id="add-to-card" class="btn sqaure_bt fll display-f">send</button>
</form>
<script>
$(document).ready(function() {
$("#myForm").submit(function(e) {
e.preventDefault();
let postData = $(this).serialize();
$.ajax({
url: 'Addtocart.php',
method: 'POST',
data: postData,
success: function(data) {
$('#result').html(data);
}
});
});
});
</script>

Submit two forms at once - Safari bug

I am trying to submit two forms at the same time using jQuery and ajax. The idea is to optin the email to a separate mailing list which is why 2 forms are needed.
It works for both Chrome and Firefox but not Safari. When I test in Safari it only submits one of the forms.
If anyone has any suggestions that would be a huge help.
My code looks like this:
HTML
<form>
<input id="email-input" type="text" name="email" value="" size="11">
<input type="checkbox" name="newsletter-signup" id="newsletter-signup">
<input id="submit-btn" type="submit" value="SignUp">
</form>
<form id="mailing-list-form">
<input type='hidden' name='email' id="hidden-email" value='' size='10'>
</form>
JS
$('#email-input').change(function() {
$('#hidden-email').val($(this).val());
});
$("#submit-btn").click(function() {
if ($("#newsletter-signup").is(':checked')) {
submitTwoForms();
} else {
//do nothing
}
});
function submitTwoForms() {
var dataObject = $('#mailing-list-form').serialize();
$.ajax({
url: "http://pacmail.em.marketinghq.net/functions/mailing_list.html",
data: dataObject,
type: "GET",
success: function() {
$('form').each(function() {
$(this).submit();
});
}
});
return false; //to prevent submit
}

Submitting two jQuery ajax form with two submit buttons

Here I just want to use two submit button in a single page, but its not sending any data through post?
<form name="form_post" id="form-post" method="post">
<label>
<span>Title *</span>
<input type="text" name="post_name" id="post-name" placeholder="Post title...." required>
</label>
<label>
<span>Body *</span>
<input type="text" name="post_body" id="post-body" placeholder="Post body...." required>
</label>
<input type="submit" id="submit_post" value="Submit Post">
</form>
Here is another form:
<form id="form_comment" method="post">
<!-- need to supply post id with hidden fild -->
<input type="hidden" name="postid" value="<?php echo $post_id ?>">
<label>
<span>Name *</span>
<input type="text" name="comment_name" id="comment-name" placeholder="Your name here...." required>
</label>
<label>
<span>Your comment *</span>
<textarea name="comment" id="comment" cols="30" rows="10" placeholder="Type your comment here...." required></textarea>
</label>
<input type="submit" id="submit_comment" value="Submit Comment">
</form>
this my script but not working? where I'm sending my request. I want to active such scrpts fro particuler submit, is there any way?
$(#form_post).submit(function(){
var form = $(form);
var submit = $('#submit_post');
form.on('submit', function(e) {
// prevent default action
e.preventDefault();
// send ajax request
$.ajax({
url: 'ajax_post.php',
type: 'POST',
cache: false,
data: form.serialize(), //form serizlize data
beforeSend: function(){
// change submit button value text and disabled it
submit.val('Submitting...').attr('disabled', 'disabled');
},
success: function(data){
// Append with fadeIn see http://stackoverflow.com/a/978731
var item = $(data).hide().fadeIn(500);
$('.wrap').append(item);
// reset form and button
form.trigger('reset');
submit.val('Submit Post').removeAttr('disabled');
},
error: function(e){
alert(e);
}
});
});
});
$(#form_comment).submit(function(){
var form = $(form);
var submit = $('#submit_comment');
form.on('submit', function(e) {
// prevent default action
e.preventDefault();
// send ajax request
$.ajax({
url: 'ajax_comment.php',
type: 'POST',
cache: false,
data: form.serialize(), //form serizlize data
beforeSend: function(){
// change submit button value text and disabled it
submit.val('Submitting...').attr('disabled', 'disabled');
},
success: function(data){
// Append with fadeIn see http://stackoverflow.com/a/978731
var item = $(data).hide().fadeIn(500);
$('.comment-block').append(item);
// reset form and button
form.trigger('reset');
submit.val('Submit Comment').removeAttr('disabled');
},
error: function(e){
alert(e);
}
});
});
});
you miss some "
it should be $("#form_comment") and $("#form_post") ...
This works for me:
$('#form_post').on('submit', function(event){
event.preventDefault();
$.ajax({
...
...
...
});
});
$('#form_comment').on('submit', function(event){
event.preventDefault();
$.ajax({
...
...
...
});
});
Use submit events like this,
$('body').on('submit', '#form_comment', function(){
e.preventDefault();
$.ajax({
...
...
...
});
});
$('body').on('submit', '#form_post', function(){
e.preventDefault();
$.ajax({
...
...
...
});
});

Repopulating div with new form/content using jQuery/AJAX

Are there any jQuery/AJAX functions that when a form (or anything for that matter) is displayed, upon pressing a button the div containing the original form is replaced by a new form? Essentially, a multi-part form without having to reload the page.
Can I use something like this?
$('form#myForm').submit(function(event) {
event.preventDefault();
$.ajax({
type: '',
url: '',
data: $(this).serialize(),
success: function(response) {
$('#divName').html(response);
//somehow repopulate div with a second form?
}
})
return false;
});
I've used this before for adding items to a list, but I've never used it to totally repopulate it with different content. How can I direct it to the second form?
edit - I got it to work, but only when I write '#form2' for the replacement. I alerted the response and I get {"formToShow":"show2"}. I tried doing response.formToShow but it's undefined.
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
</head>
<div id="divName">
<form method="POST" action = "#" id="form1">
<input type="textbox" name="textbox1" value="1"/>
<input type="submit" name="submit1"/>
</form>
<form method="POST" action = "#" id="form2" style="display: none">
<input type="textbox" name="textbox2" value="2"/>
<input type="submit" name="submit2"/>
</form>
</div>
<script>
$('form#form1').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'JSON',
url: 'receiving.php',
data: $(this).serialize(),
success: function(response) {
$('#form1').hide(); //hides
//$('#form2').show(); //this will show
$(response.formToShow).show(); //this does not display form 2
}
})
return false;
});
</script>
Here is receiving.php. When I view this page {"formToShow":"show2"} is displayed
<?php
echo json_encode(array("formToShow" => "#form2"));
?>
Check the JQuery Load Function
This is personal preference, but I'd never send HTML through the response and display it like that, what I'd do is:
Send a JSON array back from the server, such as { formToShow: "#form1" }
Then you can simply do this:
success: function(response) {
$('form').hide();
$(response.formToShow).show();
}
Obviously, using this method, you'd also have to have the second form in your markup like this:
<form method="POST" action = "#" id="form2" style="display: none">
<input type="textbox" name="textbox2"/>
<input type="submit" name="submit2"/>
</form>
You'd also have to change (to pickup the array):
$.ajax({
type: 'JSON'
try this
$('form#myForm').submit(function(event) {
event.preventDefault();
$.ajax({
type: '',
url: '',
data: $(this).serialize(),
success: function(response) {
$('#divName').html(response);
$('#form1').hide();
$('#form2').show();
}
})
return false;
});
<form method="POST" action = "#" id="form1">
<input type="textbox" name="textbox1"/>
<input type="submit" name="submit1"/>
</form>
<form method="POST" action = "#" id="form2" style="dispay:none;">
<input type="textbox" name="textbox2"/>
<input type="submit" name="submit2"/>
</form>

Adding a unique FORM name or ID to a function

is there a way of adding the form name or id to this Function to make it unique? I have a loop process that displays 5 forms and I need this piece of coding to be unique to each.
<script type="text/javascript">
$(function() {
$("input, select, textarea, checkbox, radio").autosave({
url: "/js/autosave/autosave.php",
method: "post",
grouped: false,
success: function(data) {
$("#message").html("Data updated successfully");
},
send: function(){
$("#message").html("Sending data...");
},
dataType: "html"
});
});
</script>
the form
<form action="/js/autosave/autosave.php" method="post">
<fieldset>
<label for="name">Name:<input type="text" name="word" id="word" value="<?php echo $row['word'] ?>"/></label>
<label for="email">Email:<input type="text" name="type" id="type" value="<?php echo $row['type'] ?>" /></label>
<input type="hidden" name="id" value="<?php echo $row['Id'] ?>" />
<input type="submit" value="Save changes" />
</fieldset>
</form>
Based on your updated question...
$(function() {
var formCounter = 0;
$("form:not([id])").each(function(){
$(this).attr("id", "form_" + formCounter);
formCounter++;
});
}
You could reference $(this) within autosave to get the caller and query it for its parent (and add an attribute or some identifying characteristic to each)
$(function(){
$('form').each(function(){
$(this).find('input, select, textarea, checkbox, radio').autosave({
url: "/js/autosave/autosave.php",
method: "post",
grouped: false,
success: function(data) {
$("#message").html("Data updated successfully");
},
send: function(){
$("#message").html("Sending data...");
},
dataType: "html"
});
});
});
The code above adds autosave functionality to each form individually, which should solve your issue.

Categories