AJAX code for dispatching an event does not work

I cannot get the form to submit inside the ajax success function:

$('#formId').on('submit', function (e) { 
    e.preventDefault(); 
});

$('#submit').on('click', this.doStuff);

doStuff: function () {
    $.get('url').done(function (data) {
        if (data.IsSuccessful) {
            $('#formId').off('submit');
            $('#formId').submit();
        }
        else {
        }
    });
}

It is unlikely that this will be done the second time this event is fired, but not the first, and it will be sent independently with these two lines of code, but not inside get (the debugger really hit it). How can I submit a form based on a successful ajax call?

+4
source share
2 answers

e.preventDefault();The method prevents formatting the past and redirects the ajax call. Try the following:

 $('#submit').click(function (e) {
    e.preventDefault();
    $.get('url').done(function (data) {
                if (data.IsSuccessful) {
                    $('#formId').submit();
                }
                else {

                }
        });
     });
+4
source

Fine-tuning the code:

The event submitwill handle all the logic. Therefore, no matter how your form is submitted, the event will fire.

var check = false;
$('#formId').on('submit', function (e) { 
    return check;
});

$('#submit').on('click', function(){
   $.get('url').done(function (data) {
       if (data.IsSuccessful) {
          check = true;
          $('#formId').submit();
       }
       else
       {
         check = false;
       }
    });
    return false;        
});
0

Source: https://habr.com/ru/post/1567984/


All Articles