Form OnSubmit to wait jQuery Ajax Return?

夏期劇場 picture 夏期劇場 · Jan 26, 2013 · Viewed 16.7k times · Source

I want to trigger $.ajax on form onsubmit and return true only after Ajax return is something valid.

For example:

<form id="myForm" onsubmit="return ajaxValidation();">
    <input id="myString" name="myString" type="text" />
    <input type="submit" value="Submit" />
</form>

In Javascript:

function ajaxValidation() {
    $.ajax({
        async: false,
        type: "POST",
        url: "ajax.php",
        data: { myString: $("#myString").val() }
    }).success(function( response ) {
        alert(response); //Got 'ok'
        if (response=="ok") {
            return true; //mark-1
        } else {
            alert("Oh, string is wrong. Form Submit is cancelled.");
        }
    });
    return false; //mark-2
}

When i submit, i got alert ok, but it returned 'false' because it jumped to final return false line.

Why? I can not understand. Actually, it should hit to return true line. (And, even after return true, the function should stop there and just come out of it)

So it is now means, the parent function does NOT wait to the Ajax Return. Instead, it is continuously running down to the end. Any idea why, please. How to make the parent function to be waiting the Ajax?

Answer

charlietfl picture charlietfl · Jan 26, 2013

Since AJAX is asynchronous your validation Would work better using a click handler on the submit button.

Following is based on removing the inline onSubmit

$(function() {

    var $form = $('#myForm');

    $form.find('input[type="submit"]').click(function() {
        $.ajax({
           /* async: false,  this is deprecated*/
            type: "POST",
            url: "ajax.php",
            data: {
                myString: $("#myString").val()
            }
        }).success(function(response) {
            alert(response); //Got 'ok'
            if(response == "ok") {
             /*  submit the form*/
                $form.submit();
            } else {
                alert("Oh, string is wrong. Form Submit is cancelled.");
            }
        }); /* prevent default when submit button clicked*/
        return false;

    });
});