S
S
svilkov872018-08-31 13:25:34
AJAX
svilkov87, 2018-08-31 13:25:34

How to correctly submit a form after one or another response with Ajax?

Hello!
The task is to submit the form when clicking on the button (redirect the page, etc.), but only after ajax returns the data.
Here is a piece of code with comments:

$button.on( 'click', function(e) {
        e.preventDefault(); // предотвращаем сабмит, т.к. данные еще не получены
            $.ajax( {
                url        : '/someUrl',
                type       : 'POST',
                dataType   : 'json',
                data       :  data,
                success : function( data ) {

                    if ( data.status == 'SUCCESS' ) { // тут получили данные 
                        return true; // а тут я пытаюсь сабмитить форму
                    }
                }

            } );
    } );

The submission doesn't happen. Why? How to do it right?
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Lander, 2018-08-31
@svilkov87

$button.on( 'click', function(e) {
  $.ajax( {
    url        : '/someUrl',
    type       : 'POST',
    dataType   : 'json',
    data       :  data,
    success : function( data ) {
      if ( data.status == 'SUCCESS' ) { // тут получили данные 
        $(this).closest('form').submit();
      }
    }
  } );
  return false;
} );

Doesn't it work?

S
Sergey delphinpro, 2018-08-31
@delphinpro

DO NOT handle submission like this!
The user has every right not to click your button with the mouse, but to transfer focus to it with a tab and press enter. In this case, your handler simply won't work.

$form.on( 'submit', function(e) {
        e.preventDefault();

It is not clear on the question, why do you need to submit the form a second time if you have already sent and received the data?
Want to redirect the user to another page? No problems:
location.href = 'http://yandex.ru';

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question