views:

49

answers:

2

Hello Basically I am trying to call a function (function 1), that get the results from another function (function 2). And this function 2 is making an ajax call.

So the code would be like this:

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

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

I know that is I display an alert in the success function, I get the results. But how can we make this result be sended back?

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

return msg;

thanks for your help

+2  A: 

In theory, this is possible using jQuery's async: false setting. That setting makes the call synchronous, i.e. the browser waits until it's done.

This is considered bad practice, though, because it can freeze the browser. You should re-structure your script so you can do the relevant things in the success callback instead of f1. I know this is less convenient than what you do in f1(), but it's the right way to deal with Ajax's asynchronous nature.

Pekka
A: 

You can forcefully make the request synchronous ( kinda losing the benefit of ajax ) but making your code work:

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

Otherwise, you have to add a callback in your success function if you want to keep it asynchronous..

function f2() {
    $.ajax({
        type: 'POST',
        url: '/test.php',
        async:false,
        success: function(msg){
           doSomething(msg);
        }
    });
}
meder
thanks for your answers guysAs I understand it's an asynchronous/synch issue...My purpuse was to avoid having the same AJAX call several times, when I have several different things to do on the call result.So the way I was looking for is having the AJAX function called by one, 2 or more different functions... But as I understand if I need to keep the asynchronous mode I need to do it a different way.
kire