0

In my javascript file, I use the function above to get asynchronously a value calculated by the server:

function function2(userid)
    {
        $.ajax({
                        type: "POST",
                        url: "http://localhost/bghitn/web/app_dev.php/get_number_of_articles",
                        data:{id:userid},
                        cache: false,
                        success: function(data){

                          return data;      
                        }
                        });

    }

In fact, I call the function2 inside a set of functions:

function1();
var userid=.....
var x= function2(userid);
function3(x);

The problem: as you see, function3 uses the data returned by function2. But it seems that function3 starts executing before the AJAX call is successfully finished. I tried to use the when function but in vain.

$.when(function2(userid)).done(function(){
function3();
        });

How to make the next javascript code executes after the preceding AJAX request is successfully performed? Your advices are highly appreciates.

Adib Aroui
  • 4,981
  • 5
  • 42
  • 94
  • 1
    Ajax is asynchronous, this isn't going to work. Pass a callback to the function and execute it when the ajax completes. – MightyPork Feb 10 '14 at 16:04
  • 2
    your second attempt almost works, but you have to return the promise. `return $.ajax(...)` – John Dvorak Feb 10 '14 at 16:06
  • Thank you everybody.@JanDvorak The link provided is very useful – Adib Aroui Feb 10 '14 at 16:08
  • @JanDvorak, I thought I understood you last time, but in fact, I don't. I tried your remark but in vain. Is it the same idea behind the third option in the accepted answer? – Adib Aroui Feb 20 '14 at 12:09

1 Answers1

3

Option 1: You can always set your AJAX call to be synchronius, but be ready that the whole page stucks while waiting for response. just add parameter async: false to your set of parameters.

Option 2: Provide callbacks or put your future code inside success handler

Option 3: You can use defer/promise described here http://blog.mediumequalsmessage.com/promise-deferred-objects-in-javascript-pt1-theory-and-semantics

Vova Lando
  • 558
  • 3
  • 15
  • This is it, thank you very much. I will use the info provided, in addition to the link in comments of question. – Adib Aroui Feb 10 '14 at 16:09