Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
184
rated 0 times [  187] [ 3]  / answers: 1 / hits: 16059  / 13 Years ago, thu, april 21, 2011, 12:00:00

I have a problem that is confusing me at the moment. I am using ajax to get some ID's from a website. Once it's complete I want to store the ID's in a variable for further processing. I have my code laid out like this:



var ids;

function get_ids() { ... Get the ID's from the site and store them in the global variable ids ... }

get_ids();
alert(ids.length);


As you can see ids will always be 0 because the script will continue to run before the ajax request in get_ids has had a chance to respond.



What's the best way to what I'm trying to do? I want to wait until get_ids has finished.


More From » javascript

 Answers
33

You need to make get_ids take a callback parameter and call it when it receives a response.



For example:



function get_ids(callback) {
...
response: function(data) {
...
callback(data);
}
...
}

get_ids(function(ids) {
...
});

[#92622] Tuesday, April 19, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
janjadonb

Total Points: 4
Total Questions: 114
Total Answers: 118

Location: Mali
Member since Fri, Dec 3, 2021
3 Years ago
janjadonb questions
;