Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
176
rated 0 times [  183] [ 7]  / answers: 1 / hits: 17573  / 13 Years ago, thu, november 3, 2011, 12:00:00

I'm trying to get some data from a PHP script in a project right now. All examples I found searching for AJAX callback functions use the data already in the callback itself, but I want to fetch data and store it in a way ready to be returned.



function getEle (id) {
var element = [];

$.ajax({
url: 'slides.php',
type: 'POST',
data: {id: id},
success: function(data) {
var content = data;

element[0] = id;
element[1] = content;
// if I alert(element[1]); here it will work!



}
});
alert(element[1]); // here it just won't :/ (undefined)
return element;
}


Somewhere in my script some function needs to getEle(ments) but all I get is undefined.
is there a way to do what I want? Or is there maybe a better way to do this?


More From » php

 Answers
133

A solution would be to pass a callback function to getEle():



getEle(id, callback){
$.ajax({
/* some options, */
success: function(){
var content = data;
element[0] = id;
element[1] = content;
callback(element);
}
})
}


And then pass a function containing the code of what to do when you have the element content:



getEle('myId', function(element){
alert(element[1]);
});

[#89318] Tuesday, November 1, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
keric

Total Points: 572
Total Questions: 93
Total Answers: 97

Location: Cyprus
Member since Mon, Oct 24, 2022
2 Years ago
;