I
I
Ivan Churkin2015-04-05 19:39:28
JavaScript
Ivan Churkin, 2015-04-05 19:39:28

How to execute a function after ajax post type request?

Authorization in progress.

$(document.forms['someName']).on('submit', function() {
    
    var form = $(this);
    $(':submit', form).button('loading');

    $.ajax({
        url: '/signin',
        method: 'POST',
        data: form.serialize(),
        complete: function() {
            $(':submit', form).button('reset');
        },
        statusCode: {
            200: function() {
                    window.location.href = '/';
            },
            403: function(jqXHR) {
                var error = JSON.parse(jqXHR.responseText);
                window.location.href = '/signin';
            }
        }
    });
    return false;
});

After the server responds with a 403 error, I want to redirect to the authorization page window.location.href = '/signin'and display an informational message indicating the reason for the error. At the same time, I don’t want to specify any parameters through ?, like this window.location.href = '/signin?login_fail=1'.

Thus, is it possible to call the js function only if the user came to this page after an unsuccessful post request?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Timur Shemsedinov, 2015-04-05
@ivanchurkin

UPD: a flag in cookie or localstorage will help, for example: localStorage.lastResult = "error";
Next to complete in the $.ajax call, add another error: function() {} or error: functionName if it has already been defined somewhere.

A
Alexander Tsymbal, 2015-04-05
@AlexanderTsymbal

the jquery $.ajax method has such a parameter as success (formulated in the same way as complete and statusCode) - it fires when the method succeeds: i.e. if the request is completed and some information is returned.
You can use success to process received data. I see that you are getting the response in JSON. Throw in some flag, for example "is403" with values ​​true or false. And set the flag only if the 403 worked.
then the script part will be as follows:

....
success: function(data) {
   var answer = JSON.parse(data);
   if (answer.is403 === true) {
      //делаем редирект
   } else {
      //делаем что-нибудь другое, если флаг 403 не установлен, а значит, возвращены какие-то данные
   }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question