Tutorial :How to obtain jquery post return values?


I want to retrieve the height and width of an image on a server by using an ajax post call to a php file which returns a double pipe delimited string 'width||height'

My javascript is correctly alerting that requested string from the php file so the info is now in my script but i cannot seem to access it outside the $.post function.

This works:

  var getImagesize = function(sFilename)    {      $.post("getImagesize.php", { filename: sFilename, time: "2pm" },      function(data){         alert(data.split('||'));                });    }  

But retrieving is a different matter:

// this line calls the function in a loop through images:    var aOrgdimensions = getImagesize($(this, x).attr('src')) ;  alert(aOrgdimension);    // the called function now looks like this:        var getImagesize = function(sFilename)        {          var aImagedims = new Array();          $.post("getImagesize.php", { filename: sFilename },          function(data){             aImagedims = data.split('||');                    });          return "here it is" + aImagedims ;        }  

Anyone able to tell me what i'm doing wrong?


You are misunderstanding the way that an AJAX call works. The first "A" in AJAX stands for asynchronous, which means that a request is made independent of the code thread you are running. That is the reason that callbacks are so big when it comes to AJAX, as you don't know when something is done until it is done. Your code, in the meantime, happily continues on.

In your code, you are trying to assign a variable, aOrgdimensions a value that you will not know until the request is done. There are two solutions to this:

  1. Modify your logic to reconcile the concept of callbacks and perform your actions once the request is done with.

  2. Less preferably, make your request synchronous. This means the code and page will "hang" at the point of the request and only proceed once it is over. This is done by adding async: false to the jQuery options.


Thanx for the Asynchronous explaination. I did not realize that, but at least now i know why my vars aren't available.

Edit: Figured it out. Used the callback function as suggested, and all is well. :D

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »