Solid I Solid I - 5 months ago 22
Ajax Question

Javascript - Stop form submit depending on ajax response

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

Answer

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