views:

58

answers:

3

Once again having problems being a new to javascript. I want to get the reply from my PHP script using JQuery's get. Here's my function

function getNext(){
    var returnData = null;
    $.get("get.php", {task:'next'}, function(responseText){
        returnData = responseText; }, "text");  
    return returnData;      
}

Now obviously the function returns null even though the request was successful. Why? Thanks for your help in advance.

+5  A: 

Because ajax is asynchronous, it acts independently on its own and so by the time the return statement completes, it hasn't been assigned yet.

meder
+5  A: 
function getNext(){
   var returnData;  
   $.ajax({
      url: "get.php",
      data: {task:'next'},
      success: function(responseText) { returnData = responseText },
      async: false;
   });
   return returnData;      
}

Note that this may "freeze" the UI because Javascript is single threaded -- it will wait until it receives the response from the server.

You may want to refactor it so that the action is called in the success callback. Could you show us what triggers the invokation of the getNext method?

CD Sanchez
Awesome, thanks very much. I understand(ish) now.The code is invoked by document ready, but I'm not coding anything to be used merely discovering AJAX.
Harry M
A: 

try this

function getNext(){
  var returnData = null;
  $.get("get.php", {task:'next'}, 
    function(responseText){
      returnData = responseText;
      alert('Data ' + responseText);
    });
}

You will have to poll whether returnData contains actual data that you want periodically (or put your code into the callback method)

Yarek T