vendredi 8 juillet 2016

How to stop a form from submitting until an ajax function, that was called by onSubmit, has finished


My code is below. I want the form to submit until after the ajax function has finished, that way the submit variable can be set properly. But submit always has the defaulted false value. How do I get the form to wait until the ajax call is completed and the submit variable is given a new value?

$("#CreateCandidateForm").on('submit', function (event) {
    var theFirstName = $("#FirstName").val();
    var theLastName = $("#LastName").val();
    var submit = false;

    $.ajax({
        type: "POST",
        url: "CreateSearch", // the method we are calling
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ firstName: theFirstName, lastName: theLastName }),
        dataType: "json",
        success: function (result) {
            if (result == false) {
                submit = true;
            }                     
        },
        error: function (exception) {
            event.preventDefault();
            console.log(exception);
            alert('Exception: ' + exception);        
        }
    });    
    return submit;
});

Aucun commentaire:

Enregistrer un commentaire