Tyler
Tyler

Reputation: 13

Form submit after on ajax callback

I'm trying to do an ajax call to a website before the form is submitted. If the request was succesful, I'd like the form to submit normally.

$form = $('form');

$form.submit(function() {
    $.ajax({
        url: 'http://example.com',
        data: {
            name: 'test',
            email: '[email protected]'
        },
        async: false,
        dataType: 'jsonp',
        success: function () {
            $form.unbind('submit').submit();
        },
        error: function () {
            $form.unbind('submit').submit();
        }

    });
    return false;
});

Here is a jsfiddle - http://jsfiddle.net/5ykU5/

I want it to send the reqeust to example.com. The success and error callback unbinds the form from the event and attempts to submit it.

Using this approach results in a "Uncaught TypeError: object is not a function" thrown by Jquery.

Thanks for any help!

Upvotes: 1

Views: 950

Answers (2)

mplungjan
mplungjan

Reputation: 177965

I am 99% 100% sure your submit button has

name="submit"

Please rename it to allow .submit() to be called.

No need to unbind which is now called .off

success: function () {
  $form.submit(); // or $form.off("submit").submit() if you insist
},

Also you should not use async:false - I surmise it was in desperation you added that?

Upvotes: 2

Abhas Tandon
Abhas Tandon

Reputation: 1889

Since you are using synchronous call you may do it through a flag variable:

$form = $('form');

$form.submit(function() {
    var flag=true;
    $.ajax({
        url: 'http://example.com',
        data: {
            name: 'test',
            email: '[email protected]'
        },
        async: false,
        dataType: 'jsonp',
        success: function () {
            flag=true;
        },
        error: function () {
            flag=false;
        }

    });

    return flag;

});

Upvotes: 0

Related Questions