Cannot prevent Submit based on ajax check - javascript

I am a java/jquery novice and struggling with the following:
$(document).ready(function() {
//Prevent SUBMIT if Session setting = On (Ajax)
$('#formID').submit(function(e) {
var prevent = false;
$.ajax({
type: "POST",
url: "url/to/ajax_file.php",
cache: false,
success: function(res){
if(res == "On") { alert('Session is ON so submit should be prevented'); prevent = true; }
}
});
if (stop2) { e.preventDefault(); }
});
});
The session setting is returned ok, and the alert is presented. But I also want to prevented the form submit if the session setting returned = 'On'. This is not happening. There is obviously something I do not understand, any advice?

You can't do that because of the asynchronous nature of ajax requests, instead in the submit handler you need to directly prevent the default action then in the ajax handler you can submit the form programatically.
$(document).ready(function() {
//Prevent SUBMIT if Session setting = On (Ajax)
$('#formID').submit(function(e) {
e.preventDefault();
var form = this;
$.ajax({
type: "POST",
url: "url/to/ajax_file.php",
cache: false,
success: function(res) {
if (res == "On") {
alert('Session is ON so submit should be prevented');
} else {
form.submit();
}
}
});
});
});

Related

Get the ajax return value on successful output from php as true or false [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I'm wanting to use AJAX to determine whether or not a form's values are acceptable to me (this is not form validation). The AJAX result will determine if the form is submitted or not.
Below, you'll see that I perform an AJAX call when the form is submitted and depending what is returned (either blank which is acceptable, or an error message which is not acceptable), I'd like to return true; or return false; the $("form").submit.
I suspect my trouble to be in the AJAX's success:. Please help me get the result out of the AJAX call so that I can do something like if (result == "") { return true; } else { return false; }.
WORKING:
$("form").submit(function(e) {
e.preventDefault();
var form = this;
var tray = $('select[name=tray_id]').val();
$.ajax({
type: "POST",
url: "modules/reserve-check.php",
data: {tray_id: tray},
cache: false
}).done(function(result) {
if (result == "")
form.submit();
else
alert(result);
}).fail(function() {
alert('ERROR');
});
});
ORIGINAL:
$("form").submit(function() {
var tray = $('select[name=tray_id]').val();
$.ajax({
type: "POST",
url: "modules/reserve-check.php",
data: {tray_id: tray},
cache: false,
success: function(result) {
alert(result);
},
error: function(result) {
alert(result); //This works as expected (blank if acceptable and error msg if not acceptable)
}
});
/*
if (result == "")
return true;
else
return false;
*/
return false; //this is here for debugging, just to stop the form submission
});
As the ajax call is asynchronous, you have to prevent the form from submitting, and then when a result is returned, you check if it matches the condition and submit the form with the native submit handler, avoiding the preventDefault() in the jQuery event handler :
$("form").submit(function(e) {
e.preventDefault();
var self = this,
tray = $('select[name=tray_id]').val();
$.ajax({
type: "POST",
url: "modules/reserve-check.php",
data: {tray_id: tray},
cache: false
}).done(function(result) {
if (result == "") self.submit();
}).fail(function() {
alert('error');
});
});
use e.preventDefault(); to prevent the form from submitting, and then use this.submit() (isn't calling the jQuery .submit() trigger function, but rather the native <form> .submit() function) to submit the form.
$("form").submit(function(e) {
e.preventDefault();
var tray = $('select[name=tray_id]').val();
var form = this;
$.ajax({
type: "POST",
url: "modules/reserve-check.php",
data: {tray_id: tray},
cache: false,
complete : function(result){callback(result, form)}
});
});
var callback = function(result, form){
if(!result)
form.submit();
};

Only send post/get if form values has changed

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');
}
});
...

Stop an ajax request from posting data until a response is received?

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
}
});
}
}

How can I disable/enable form submit in an ajax request

I'm trying first disabling form submission before the request starts and then on success enable again the form submit
this is my code:
$.ajax({
beforeSend:function(){
//disable form
$('form').on('submit',function(){
return false;
});
},
success:function(){
//enable form
$('form').on('submit',function(){
return true;
});
},
complete:function(){
//enable form
$('form').on('submit',function(){
return true;
});
,
});
it seems not working on success and complete, the form is disabled but not enabled then.
I'm using latest jQuery version.
Better use different strategy: Set a global variable to decide whether or not to submit the form. Then check it while submitting the form.
var canSubmit = 1;
$.ajax({
beforeSend:function(){
//disable form
canSubmit = 0;
},
success:function(){
//enable form
canSubmit = 1;
},
complete:function(){
//disable form
canSubmit = 1;
});
$('form').on('submit',function() {
if (!canSubmit) {
return false;
}
});
jQuery events normally support multiple handlers so you would need to turn the previous event handlers off before attaching a new one.
To use off you need to keep a reference to your handler e.g.
var myForm = $("form"),
enableSubmit = function(event) { return true; },
disableSubmit = function(event) { return false; },
ajaxCompleteHandler = function() {
myForm.off(disableSubmit);
myForm.on(enableSubmit);
};
myForm.on(enableSubmit);
$.ajax({
beforeSend: function() {
myForm.off(enableSubmit);
myForm.on(disableSubmit);
},
success: ajaxCompleteHandler,
error: ajaxCompleteHandler,
complete: ajaxCompleteHandler //you might get away with just this as I believe it's called for success and failure
});
Alternatively you could just disable the submit button ($("mybutton").prop("disabled", true))which should be more intuitive to the user.
Instead of doing a return false in beforeSend try this
$('form').on('submit',function(e){
e.preventDefault();
return false;
});
Once you return false on the submit button,it is obvious that you cannot again invoke submit operation, because the form is not now able to submit info.
The another solution is that use onclick function,like below :
Javascript file
function savecustomquestion(){
$.ajax({
type : 'POST',
url : 'customquestion.php',
data:{tablename:$('#productname').val(),name:$('#uname').val(),email_address:$('#email').val(),voucher_code:$('#voucher_code').val(),question:$('#customquestion').val()},
success: function(response){
console.log("yes");
},
error : function(response){
console.log(response);
}
});
}
HTML code
<button type="button" id="customquestionbutton" class="span2" onclick="savecustomquestion()">Verstuur</button>
PHP code
mysql_select_db('mydatabase',$connect);
if(!isset($_POST['voucher_code'])){
$voucher_code = "";
}
else{
$voucher_code = $_POST['voucher_code'];
}
$email_address = $_POST['email_address'];
$name = $_POST['name'];
$question = $_POST['question'];
$tablename = $_POST['tablename'];
mysql_query("insert into customquestion (voucher_code,email_address,name,question) VALUES('$voucher_code','$email_address','$name','$question') ");

jQuery - Resume form submit after ajax call

Is it possible to stop a form from submitting and then resubmitting the same form from within the success of an ajax call?
At the moment it gets to the success bit but it doesn't resubmit the form which should submit and redirect the user to the http://example.com website.
Thank you very much for any help in advance
If it's not possible to do it this way, is there another way of getting it to work?
$(document).ready(function() {
$('form').submit(function(e) {
e.preventDefault();
$.ajax({
url: $('form').attr('action'),
type: 'post',
data: $('form').serialize(),
success: function(data) {
if (data == 'true')
{
$('form').attr('action', 'http://example.com');
$('form').unbind('submit').submit(); // mistake: changed $(this) to $('form') - Problem still persists though it does not resubmit and redirect to http://example.com
}
else
{
alert('Your username/password are incorrect');
}
},
error: function() {
alert('There has been an error, please alert us immediately');
}
});
});
});
Edit:
Stackoverflow posts checked out for the code below:
Resume form submission after $.ajax call
How to reenable event.preventDefault?
I just thought I'd mention I have also tried this code without avail.
var ajaxSent = false;
$(document).ready(function() {
$('form').submit(function(e) {
if ( !ajaxSent)
e.preventDefault();
$.ajax({
url: $('form').attr('action'),
type: 'post',
data: $('form').serialize(),
success: function(data) {
if (data == 'true')
{
alert('submit form');
ajaxSent = true;
$('form').attr('action', 'http://example.com');
$('form').submit();
return true;
}
else
{
alert('Your username/password are incorrect');
return false;
}
},
error: function() {
alert('There has been an error, please alert us immediately');
return false;
}
});
});
});
I have also tried this code without any luck as well.
$(document).ready(function() {
$('form').submit(function(e) {
e.preventDefault();
$.ajax({
url: $('form').attr('action'),
type: 'post',
data: $('form').serialize(),
success: function(data) {
if (data == 'true')
{
$('form').attr('action', 'http://example.com');
$('form').unbind('submit').submit();
return true;
}
else
{
alert('Your username/password are incorrect');
return false;
}
},
error: function() {
alert('There has been an error, please alert us immediately');
return false;
}
});
});
});
Solution was quite simple and involved adding and setting async to false in .ajax(). In addition, I have re-worked the code to work of the submit button instead which submits the form when the AJAX passes successfully.
Here is my working code:
$(document).ready(function() {
var testing = false;
$('#btn-login').on('click', function() {
$.ajax({
url: $('form').attr('action'),
type: 'post',
data: $('form').serialize(),
async: false,
success: function(data) {
if (data == 'true')
{
testing = true;
$('form').attr('action', 'https://example.com');
$('form').submit();
}
else
{
alert('Your username/password are incorrect');
}
},
error: function() {
alert('There has been an error, please alert us immediately');
}
});
return testing;
});
});
It's no good practice to reselect all form tags throughout your code, what if you have multiple forms on the page?
Also you'd better use .on() and .off() with jQuery.
$(document).ready(function() {
$('form').on('submit', function(e) {
e.preventDefault();
// cache the current form so you make sure to only have data from this one
var form = this,
$form = $(form);
$.ajax({
url: form.action,
type: form.method,
data: $form.serialize(),
success: function(data) {
if (data == 'true')
{
$form.attr('action', 'http://example.com').off('submit').submit();
}
else
{
alert('Your username/password are incorrect');
}
},
error: function() {
alert('There has been an error, please alert us immediately');
}
});
});
});
In one line you use $('form') to select the form to change its action, but then you use $(this) to try to select that same form. I would guess that this inside the callback function isn't what you expect it to be, and is something other than your form (possibly the window object).
Just chain the calls:
$('form').attr('action', 'http://example.com').unbind('submit').submit();

Categories