views:

12

answers:

1

I did this function for get results of a query directly in an useful datastructure. The problem is the follow: in the first console.log() call , inside the callback function, the stored_data var contains the exact results, in the second console.log() call the stored_data variable looks like not initialized. Suggestions?? Below the code:

function dojo_query_mysql(query_string) {
      //The parameters to pass to xhrPost, the message, and the url to send it to
      //Also, how to handle the return and callbacks.
      var stored_data;
     var raw_data = new Object;
      var xhrArgs = {
      url: "query.php",
      postData: query_string,
      handleAs: "text",
      load: function(data) {
          raw_data = dojo.fromJson(data);
          stored_data = new dojo.data.ItemFileReadStore({data: raw_data});
    console.log(stored_data);
       },
      error: function(error) {
          //We'll 404 in the demo, but that's okay.  We don't have a 'postIt' service on the
          //docs server.
          //stored_data = error;
        }
      }
      //Call the asynchronous xhrPost
      var deferred = dojo.xhrPost(xhrArgs);
    console.log(stored_data);
      return stored_data;
    }
A: 

I have just remembered that the function doesn't wait the end of the callback execution, for wait the callback end just do a little change to the code:

var xhrArgs = {
      url: "query.php",
sync: true, // THIS IS FORCE THE SYNCRONIZATION BETWEEN THE CALLBACK AND THE CODE
      postData: query_string,
      handleAs: "text",
      load: function(data) {
          raw_data = dojo.fromJson(data);
          stored_data = new dojo.data.ItemFileReadStore({data: raw_data});
    console.log(stored_data);
       },
      error: function(error) {
          //We'll 404 in the demo, but that's okay.  We don't have a 'postIt' service on the
          //docs server.
          //stored_data = error;
        }
      }
carpediem