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!
$.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.
…
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).