I have problem to return array in jquery. I used ajax to response data from mysql and I have to add it do array and return.
This is my code:
function addOption()
{
itemsarray = [];
$.ajax({
type: "POST",
url: "",
data:{
option: 'com_zamowienia',
view: 'zamowienia_lista',
task: 'getStatusy'
},
success: function(data){
var obj = $.parseJSON(data);
for (x=0; x<obj.length; x++) {
itemsarray.push(obj[x].nazwa);
}
}
});
return itemsarray;
}
When I use : alert(addOption()). I see empty alert
asked Sep 18, 2012 at 15:52
marczak
4892 gold badges8 silver badges17 bronze badges
-
By default, AJAX calls are asynchronous. You can not return the results from the function, as it has not happened at the time it finishes.Orbling– Orbling2012年09月18日 15:54:59 +00:00Commented Sep 18, 2012 at 15:54
1 Answer 1
As AJAX is asynchronous, so you can't return array like that.
So, you should use callback function to get the array:
function addOption(callback)
{
itemsarray = [];
$.ajax({
type: "POST",
url: "",
data:{
option: 'com_zamowienia',
view: 'zamowienia_lista',
task: 'getStatusy'
},
success: function(data){
var obj = $.parseJSON(data);
for (x=0; x<obj.length; x++) {
itemsarray.push(obj[x].nazwa);
}
// return you itemsarray through callback function parameter
callback(itemsarray);
}
});
}
Call the function like:
addOption(function(myarr) {
console.log( myarr );
});
answered Sep 18, 2012 at 15:54
thecodeparadox
87.2k22 gold badges143 silver badges164 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js