0

I have a form submit handler that needs to make an AJAX call before the "default" form submit occurs.

$('#form').on('submit', function (event) {
    { ... }
    $.ajax({
        type: "POST",
        data: data,
        url: "/submit"
    }).done(function() {
        { ... }
        // Do default form action here
        return true;
    });
});

The code above the ajax call runs, but as soon as the ajax call is made the form is submitted and I'm redirected to the action URL.

How can I prevent the default form submit from occurring until the after the AJAX callback is called?

Saksham
  • 9,037
  • 7
  • 45
  • 73
Nathan Jones
  • 4,904
  • 9
  • 44
  • 70
  • possible duplicate of [AJAX request before regular form is being submitted](http://stackoverflow.com/questions/17885843/ajax-request-before-regular-form-is-being-submitted) – showdev Aug 25 '14 at 17:39
  • 1
    This always seems like a horrible pattern, why submit it twice? – epascarello Aug 25 '14 at 17:41
  • I'm creating a plugin to a 3rd party system that is modifying data from a few different sources. It is a horrible pattern, but I don't know of another way with this system. – Nathan Jones Aug 25 '14 at 17:48

1 Answers1

0

Add async: false parameter to your ajax method. This will make your call synchronous and form will be submitted right after ajax request finishes.

Vitalii Petrychuk
  • 14,035
  • 8
  • 51
  • 55
  • Setting ajax requests to synchronized is never a good choice. Let me quote: "JavaScript runs in the UI thread of the browser and any long running process will lock the UI, making it unresponsive. Additionally, there is an upper limit on the execution time for JavaScript and the browser will ask the user whether to continue the execution or not. All of this is really bad user experience. The user won't be able to tell whether everything is working fine or not. Furthermore the effect will be worse for users with a slow connection." More http://stackoverflow.com/a/14220323/1306083 – Attila Kling Aug 25 '14 at 18:36