I have tried everything. I find other questions but no answer solves my problem:
$(document).on('submit', 'form#formNuevoContacto', function(event) {
var $form = $(this);
var $accionActual = $form.find('#action');
$form.find('#action').val('validate');
$.post($form.attr("action"), $form.serialize(), function(response) {
if (response.resultValidation == "true") {
$form.submit(); // ==> INFINITE LOOP!
} else {
alert('Form is not valid!');
}
});
event.preventDefault();
});
I tried: $form.unbind().submit() but didn't work.
You could use a toggle to selectivelly pre-process the submit or otherwise let the browser do its job; In the edit bellow, just before issuing the second submit I place a variable in the form object called "isPreProcessing". As you can see, the first thing the code does is to check if this value is present, and if so, delegate the submit to the browser.
$(document).on('submit', 'form#formNuevoContacto', function(event) {
if(this.isPreProcessing) {
//allow for actual submit to run
this.isPreProcessing = false;
return;
}
var $form = $(this);
var $accionActual = $form.find('#action');
$form.find('#action').val('validate');
$.post($form.attr("action"), $form.serialize(), function(response) {
if (response.resultValidation == "true") {
//prevent the loop
this.isPreProcessing = true;
$form.submit();
} else {
alert('Form is not valid!');
}
});
event.preventDefault();
});
You should just do a single ajax call, and handle the error if it doesn't validate. If the server validates it, the server should then store it. It is messy code as you have it now, and it is also a waste of an ajax call/waste of time. You're posting the exact same data twice
$.ajax({
type: {most like put 'POST' here},
url: {action url},
data: {your form},
success: success_function(),
error: error_function()
});
Related
I have a script that sends my form via php-ajax. It does return success but what I need it to do when it has been successful is clear all the form data and close the div and load another one. I have tried many different ways to clear form and close div but they just seem to stop it working totally. The id of the div to close is '5box' The working script that i need to add these to is :
$(document).ready(function() {
$('#btn-finish').on('click', function() {
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Processing...');
var form = $(this);
$.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: form.serialize(),
success: function(result){
if (result == 'success'){
$('.output_message').text('Message Sent!');
} else {
$('.output_message').text('Error Sending email!');
}
}
});
// Prevent default submission of the form after clicking on the submit button.
return false;
});
});
Any ideas would be appreciated
To clear the form you can call the reset() method of the underlying Element. I'm not sure what you mean by 'close the div', but you can call hide() to make it disappear. Try this:
success: function(result) {
if (result == 'success') {
$('.output_message').text('Message Sent!');
form[0].reset();
$('#5box').hide();
} else {
$('.output_message').text('Error Sending email!');
}
}
Also note that it would be much better practice to return JSON from the AJAX call. You can then have a boolean flag to show the state of the request.
Update
<button name ='send' value="Send" type='submit' class='btn btn-primary'>Finish</button>
Given that is the code of your button there is another issue - you're not preventing the form from being submit, hence the AJAX request is cancelled. To do this, hook to the submit event of the form instead of the click of the button. From there you can call e.preventDefault() to stop form submission. Try this:
<script>
$(function() {
$('form').on('submit', function(e) {
e.preventDefault();
$('.output_message').text('Processing...');
var form = $(this);
$.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: form.serialize(),
success: function(result) {
if (result == 'success') {
$('.output_message').text('Message Sent!');
form[0].reset();
$('#5box').hide();
} else {
$('.output_message').text('Error Sending email!');
}
}
});
});
});
</script>
Note I used a generic 'form' selector above. You can change that to a class or id selector on the form as required.
For clearing form fields
$("input[type=text], textarea").val("");
cheers
you can also use Triggers as well
$('#form_id').trigger("reset");
I want to prevent multiple ajax calls (user holds enter key down or multi presses submit or other)
I'm thinking, the best way is to use a var with the previous form post values and compare them at each click/submit.. Is it the same? : Then do nothing
But I don't know how to go about it
Here is my javascript/jquery:
$('form').submit(function() {
$theform = $(this);
$.ajax({
url: 'validate.php',
type: 'POST',
cache: false,
timeout: 5000,
data: $theform.serialize(),
success: function(data) {
if (data=='' || !data || data=='-' || data=='ok') {
// something went wrong (ajax/response) or everything is ok, submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
} else {
// ajax/response is ok, but user input did not validate, so don't submit
console.log('test');
$('#jserrors').html('<p class="error">' + data + '</p>');
}
},
error: function(e) {
// something went wrong (ajax), submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
}
});
return false;
});
Not very creative with naming vars here:
var serial_token = '';
$('form').submit(function() {
$theform = $(this);
if ($(this).serialize() === serial_token) {
console.log('multiple ajax call detected');
return false;
}
else {
serial_token = $(this).serialize();
}
$.ajax({
url: 'validate.php',
type: 'POST',
cache: false,
timeout: 5000,
data: $theform.serialize(),
success: function(data) {
if (data=='' || !data || data=='-' || data=='ok') {
// something went wrong (ajax/response) or everything is ok, submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
} else {
// ajax/response is ok, but user input did not validate, so don't submit
console.log('test');
$('#jserrors').html('<p class="error">' + data + '</p>');
}
},
error: function(e) {
// something went wrong (ajax), submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
}
});
return false;
});
You could combine this with a timeout/interval function which aborts the submit, but the code above should just compare the data in the form
If you have some kind of submit button, just add a class 'disabled' to it when you start the ajax call, and check if it is present before trying to make the call. Remove the class when the server gives a response. Something like:
...
$theform = $(this);
$button = $theform.find('input[type=submit]');
if ($button.hasClass('disabled')) {
return false;
}
$button.addClass('disabled');
$.ajax({
....
},
complete: function () {
$button.removeClass('disabled');
}
});
...
i have written a basic commenting system which is a simple write to database form and it uses ajax as well.
The issue is that if i enter my message, and then spam send / the enter key it seems to stack up and then everything is written to the database multiple times.
My ajax is like so:
$(document).ready(function(){
$(document).on('submit', '.addcomment', function() {
var $targetForm = $(this);
$.ajax({
type: "POST",
url: "process/addcomment.php",
data: $targetForm.serialize(),
dataType: "json",
success: function(response){
if (response.databaseSuccess == true) {
$("#container").load("#container");
$targetForm.find('#addcommentbutton').attr("disabled", true);
}
else {
$ckEditor.after('<div class="error">Something went wrong!</div>');
}
}
});
return false;
});
});
The submit button does become disabled, but the form can still be entered via the enter keyboard button or even still with a mass spam of the submit button (which is supposed to be disabled)
Is there a way to 100% disable this form with jquery, until the success JSON message is received?
Anymore code just let me know!
In this case, i would not use delegation. I would instead bind the event directly to the form using .one since each form should submit only once (if that's the case.) If you instead only have one addComment form, then i question why you are using delegation in the first place.
$(commentForm).appendTo(selector).one("submit",function(e){
e.preventDefault(); // prevent this submit
$(this).submit(false); // prevent future submits
// submit data to server
})
Just keep track of if a request is in progress:
$(document).ready(function(){
var isSubmitting = false;
$(document).on('submit', '.addcomment', function() {
var $targetForm = $(this);
if (!isSubmitting) {
isSubmitting = true;
$.ajax({
...
success: function(response){
...
},
complete: function() { isSubmitting = false; }
});
}
});
There are lots of ways to handle this, but the best involves validating the data on the server end. You want to prevent people from overloading the database inadvertently (the "fat finger" problem) or deliberately (the bored script kiddie who decides to crash your server or fill your database with garbage).
The best solution:
Generate a one-time token when the page is requested (called a "nonce")
Post that nonce when you post the data
Only accept it on the server side if the nonce has never been used
This obviously requires you to keep track of a list of valid nonces, but it prevents any glitches or abuse of the send button.
Also, as others have pointed out, disable the button much earlier and only run the submit action handler once. That will help with the inadvertent double-clicks and so on, but you also need the nonce to prevent compulsive clickers or intentional misuse.
Can you do it like below:
$(document).ready(function(){
var isAjaxInProgress = null;
$(document).on('submit', '.addcomment', function() {
var $targetForm = $(this);
if(isAjaxInProgress === null || !$isAjaxInProgress ){
isAjaxInProgress = true;
$.ajax({
type: "POST",
url: "process/addcomment.php",
data: $targetForm.serialize(),
dataType: "json",
success: function(response){
if (response.databaseSuccess == true) {
$("#container").load("#container");
$targetForm.find('#addcommentbutton').attr("disabled", true);
}
else {
$ckEditor.after('<div class="error">Something went wrong!</div>');
}
isAjaxInProgress = false;
}
});
}
return false;
});
});
// declare a global ajax request variable
var is_request_sent = false;
function send_msg()
{
if(is_request_sent == false)
{
$.ajax({
type: "POST",
url: "process/addcomment.php",
data: $targetForm.serialize(),
dataType: "json",
success: function(result){
//alert(result);
is_request_sent = false;
},
error: function(a,b,c)
{
is_request_sent = false;
},
beforeSend: function(jqXHR, plain_jqXHR){
// set request object
is_request_sent = jqXHR;
// Handle the beforeSend event
},
complete: function(){
// update global request variable
is_request_sent = false;
// Handle the complete event
}
});
}
}
I have a form that, when submitted, goes through the usual e.preventDefault() and sends an ajax request instead. However, if this ajax request returns a certain condition, I want the form to be submitted normally. How do I achieve this?
// Submit handler
$(".reserveer_form").submit(function(event){
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
data: $(this).serialize(),
success: function(data) {
if($(".messagered",data).length > 0){
var errors = $(".messagered",data);
$(".gegevens").before(errors);
} else {
// SUBMIT THE FORM!
}
}
});
})
Invoke the native submit method on the form, so that it doesn't trigger the jQuery handler.
$.ajax({
context: this, // <-- set the context.
url: $(this).attr("action"),
data: $(this).serialize(),
success: function (data) {
if ($(".messagered", data).length > 0) {
var errors = $(".messagered", data);
$(".gegevens").before(errors);
} else {
this.submit(); // <-- submit the form
}
}
});
Since your comment says you change a form variable, you could start your submit handler by checking that same form variable. If it is changed, just return true. If not, continue with the current handler.
You can use the submit() method or forms:
$(".reserveer_form").submit(function(event){
event.preventDefault();
var form = this,
$form = $(form);
$.ajax({
url: $form.attr("action"),
data: $form.serialize(),
success: function(data) {
var errors = $(".messagered", data);
if (errors.length > 0){
$(".gegevens").before(errors);
} else {
form.submit();
}
}
});
})
However, this seems to be a strange ajax request. First, you send the form (serialized, via ajax) to the server, and when the response contains no errors you send it again? The server would process it twice (and act twice, depending on your form). Also, the user does not get a message that his input is already processed - he clicks "submit", and it always takes a time until it is visibly submitted (where he even could change some input).
I have a form that submits shopping cart data to a payment gateway (WorldPay) payment processing page. I need to perform a couple of extra logic the moment the custom decides to proceed to the payment but before the form submission itself. Basically, I simply want to generate a unique reference to the order at the very last moment.
Here is the jQuery code for the submit event:
$(function(){
$('#checkout-form').submit(function(e){
var $form = $(this);
var $cartIdField = $('#cartId');
console.log($cartIdField.val());
if($cartIdField.val() == ''){
e.preventDefault();
$.ajax({
url: baseUrl + '/shop/ajax/retrieve-shopping-cart-reference/',
data: {}, type: 'post', dataType: 'json',
success: function(json){
if(json.error == 0){
$('#cartId').val(json.data.cart_reference_number);
$form.submit();
}else{
alert(json.message);
}
}
});
}else{
console.log('Submitting form...'); //Does not submit!
}
});
});
The problem is that during the second submit triggered within the success: clause, the form isn't submitted still. I am assuming event.preventDefault() persists beyond the current condition.
How can I get around this?
For performe the any operation before form submit i used the following menthod hope it wil help
$('#checkout-form').live("submit",function(event){
//handle Ajax request use variable response
var err =false;
var $form = $(this);
//alert($form);
var values = {};
$.each($form.serializeArray(), function(i, field) {
values[field.name] = field.value;
});
//here you get all the value access by its name [eg values.src_lname]
var $cartIdField = $('#cartId');
console.log($cartIdField.val());
if($cartIdField.val() == ''){
$.ajax({
// your code and condition if condition satisfy the return true
// else return false
// it submit your form
/*if(condition true)
{
var err =true;
}
else
{
var err = false;
}*/
})
}
else
{
return true;
}
if(err)
{
return false
}
else
{
return true;
}
})
e.preventDefault() remove default form submit attribute which can not be reverted if applied once.
Use below code instead to prevent a form before submitting. This can be reverted.
$('#formId').attr('onsubmit', 'return false;');
And below code to restore submit attribute.
$('#formId').attr('onsubmit', 'return true;');
Only call e.preventDefault() when you really need to:
if(not_finished_yet) {
e.preventDefault();
}