AJAX request before regular form is being submitted

后端 未结 2 910
时光取名叫无心
时光取名叫无心 2021-02-01 08:50

I have a jQuery form validation script that is executed while user is trying to submit. I would like another function with AJaX request to be executed (and completed) after the

2条回答
  •  借酒劲吻你
    2021-02-01 09:14

    You want to first ensure the form is not being submitted, then run your ajax call, and if the call is successful, proceed to submit. Note I removed the ajax call from zgoslip and put it in the submit handler for the form. you can restructure it the way you want:

    $('form').submit(function(e) { 
    
         // this code prevents form from actually being submitted
         e.preventDefault();
         e.returnValue = false;
    
         // some validation code here: if valid, add podkres1 class
    
         if ($('input.podkres1').length > 0) { 
            // do nothing
         } else {
    
            var $form = $(this);
    
            // this is the important part. you want to submit
            // the form but only after the ajax call is completed
             $.ajax({ 
                 type: 'post',
                 url: someUrl, 
                 context: $form, // context will be "this" in your handlers
                 success: function() { // your success handler
                 },
                 error: function() { // your error handler
                 },
                 complete: function() { 
                    // make sure that you are no longer handling the submit event; clear handler
                    this.off('submit');
                    // actually submit the form
                    this.submit();
                 }
             });
         }
    });
    

提交回复
热议问题