Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use the jQuery $.ajax function to stop or allow a form submit?

Tags:

jquery

ajax

$('#post_form').submit(function() {
    $("#ajax_bar_loader").show();
    $.ajax({
        url: 'add.html',
        data: $('#post_form').serialize(),
        dataType: 'json',
        type: 'post',
        success: function( result ) {
            retVal = formCheck( result );
        }
    });

    return false;
});

That's what my code looks like and instead of the "return false", I want to allow it if the data contained in "result" says to. How can I accomplish this?

like image 980
Shamoon Avatar asked Mar 05 '10 00:03

Shamoon


2 Answers

You could do it like this:

$.ajax({
    url: 'add.html',
    data: $('#post_form').serialize(),
    dataType: 'json',
    type: 'post',
    success: function( result ) {
        retVal = formCheck( result );
        if(retVal)
          $('#post_form').unbind('submit').submit();
        else
          alert('Error with your form! Oh crap!');
    }
});

Since you're posting back and leaving, this just unbinds this handler if successful and lets the submit happen normally when invoking it, so the code doesn't run and check again, it just submits.

like image 179
Nick Craver Avatar answered Sep 24 '22 10:09

Nick Craver


I would suggest always returning false at the end of the event handler in order to prevent normal form submission. Within the success callback to $.ajax, you could conditionally redirect based on the response from the server:

$('#post_form').submit(function() {
    $("#ajax_bar_loader").show();
    $.ajax({
        url: 'add.html',
        data: $('#post_form').serialize(),
        dataType: 'json',
        type: 'post',
        success: function( result ) {
            if(result == 'something') {
                alert("some error happened");
            } else {
                // assuming we're visiting the form's action
                window.location.href = $(this).attr("action");
            }
        }
    });
    return false;
});

Relying on the success callback to fire before the submit handler completes execution is unrealistic, since the code following the $.ajax call is very likely to be evaluated before the success callback executes ($.ajax will run asynchronously).

like image 24
karim79 Avatar answered Sep 21 '22 10:09

karim79