0

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?

Community
  • 1
  • 1
Andrei RRR
  • 3,068
  • 16
  • 44
  • 75
  • 4
    AJAX is asynchronous, so your function can't really `return` anything. – Blender Jan 20 '13 at 16:35
  • Blender, how else can I retrive that information without appending it to the html? There must be a way... – Andrei RRR Jan 20 '13 at 16:40
  • Create a global variable and assign it the result from the getJSON call. But note that the variable will not be populated until the call has returned successfully, so typically whatever action you do with the data returned from the getJSON call is run from within the callback itself. – mccannf Jan 20 '13 at 16:49

1 Answers1

1

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 the return result and put all your functionality that needed to handle the results inside the callback function/or call other functions from it....

yoav barnea
  • 5,836
  • 2
  • 22
  • 27