Reputation:
I declared a global variable var idCategories= new Array();
in my file.js
I use it in this function
function test() {
$.ajax({
type: "GET",
url: "http://my_site/api/categories?ws_key="
+ ws_key
+ "&PHP_AUTH_USER=" + PHP_AUTH_USER,
dataType: "xml",
success: parseXml
});
function parseXml(xml) {
var i = 0;
$(xml).find("category").each(function () {
idCategories[i] = $(this).attr('id');
// length increments at each iteration
alert("length=" + idCategories.length);
i = i + 1;
});
}
alert("length=" + idCategories.length); //returns 0
}
in the function parseXml(xml)
the array length is well incremented but outside of this function length = 0! so that I can't use the array idCategories
in another function!
Upvotes: 1
Views: 686
Reputation: 54618
The problem is that the AJAX call is ASYNC. So parseXml
will most likely, if not always, be called after your alert is called.
Why not:
function test() {
$.ajax({
type: "GET",
url: "http://my_site/api/categories?ws_key="
+ ws_key
+ "&PHP_AUTH_USER=" + PHP_AUTH_USER,
dataType: "xml",
success: parseXml
});
function parseXml(xml) {
var i = 0;
$(xml).find("category").each(function () {
idCategories[i] = $(this).attr('id');
// length increments at each iteration
alert("length=" + idCategories.length);
i = i + 1;
});
alert("length=" + idCategories.length); //returns 0
}
}
Upvotes: 3
Reputation: 2339
try to using object and array
function parseXml(xml) {var obj={};var a = [];
$(xml).find("category").each(function(i) {
obj["idCategory"]= $(this).attr('id');
a.push(obj);
alert("length="+a.length);// length increments at each iteration
});
}
alert("length="+a.length);//returns 0
}
Upvotes: 1
Reputation: 5272
$.ajay is by default asynchronus function! That means thet when it starts to execute it does not block application flow. you're alert statement executes before $.ajax success function. You have two solutions.
set asny parameter to false.
$.ajax({
type: "GET",
async: false,
...
call alert in parseXml function.
I belive you're best bet is async:false, but correct way of doing it would be to advance script execution after $.ajax call is finished (execute next step in parsexml function).
Upvotes: 1
Reputation: 48793
Ajax is asyncronous. Your alert("length="+idCategories.length);
code is called before response is delivered.
Upvotes: 0
Reputation: 207501
This question appears multiple times a day. You are making an asynchronous call, that alert line fires BEFORE the Ajax call is returned.
Upvotes: 0