Possible Duplicate:
Variable doesn’t get returned from AJAX function
I have this function:
function getCompanyName(companyID) {
$.getJSON('http://www.domain.com/' + companyID + '.json', function(companyData) {
$.each(companyData, function(i,item){
result = item.name;
});
return result;
});
};
If I call it like getCompanyName(13) the result is undefined and if I access www.domain.com/13.json, I get this result:
[
{
id: 13,
category_id: 2,
name: "Company Name",
phone: "333-333-3333",
address: "Address",
description: "Description",
logo_url: "/system/businesses/logos/000/000/013/thumb/G13.jpeg?1348191485"
}
]
Someone can tell me what I am doing wrong here?
your getCompanyName() function will finished execute very fast. long before the ajax request complete.
so if you write somthing like this:
var
a=getCompanyName(companyID);, the result will be undefined because the response didn’t return yet from the server.(although you were already exit from the getCompanyName() function )to make long story short, you need to wate until the ajax responde complete (and not until the
getCompanyName(companyID)function finished,- delete thereturn resultand put all your functionality that needed to handle the results inside the callback function/or call other functions from it….