How to get the result of jQuery AJAX call, then call another function

Basically I am trying to call a function (function 1) that gets results from another function (function 2). And this function 2 makes an ajax call.

So, the code will be like this:

function f1 () {
    var results = f2();
}

function f2() {
    $.ajax({
        type: 'POST',
        url: '/test.php',
        success: function(msg){
        }
    });
}

I know that I show a warning in the function of success, I get the results. But how can we bring this result back?

I tried to do something like this inside function 2 without success:

return msg;

thanks for the help

+3
source share
2 answers

In theory, this is possible using the jQuery setup async: false. This parameter makes a synchronous call, i.e. The browser waits until it is executed.

, . script, success f1. , , , f1(), Ajax.

+4

( ajax), :

function f2() {
    var ret = false;
    $.ajax({
        type: 'POST',
        url: '/test.php',
        async:false,
        success: function(msg){
           ret = msg
        }
    });
    return ret;
}

success, .

function f2() {
    $.ajax({
        type: 'POST',
        url: '/test.php',
        async:false,
        success: function(msg){
           doSomething(msg);
        }
    });
}
+2

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


All Articles