sending an ajax request before form submit

Solutions on MaxInterview for sending an ajax request before form submit by the best coders in the world

showing results for - "sending an ajax request before form submit"
Erica
15 Oct 2016
1$('form').submit(function(e) { 
2
3     // this code prevents form from actually being submitted
4     e.preventDefault();
5     e.returnValue = false;
6
7     // some validation code here: if valid, add podkres1 class
8
9     if ($('input.podkres1').length > 0) { 
10        // do nothing
11     } else {
12
13        var $form = $(this);
14
15        // this is the important part. you want to submit
16        // the form but only after the ajax call is completed
17         $.ajax({ 
18             type: 'post',
19             url: someUrl, 
20             context: $form, // context will be "this" in your handlers
21             success: function() { // your success handler
22             },
23             error: function() { // your error handler
24             },
25             complete: function() { 
26                // make sure that you are no longer handling the submit event; clear handler
27                this.off('submit');
28                // actually submit the form
29                this.submit();
30             }
31         });
32     }
33});