I try to load a local XML File with Jquery, with this function:
function initXML()
{
var returnVal;
$.ajax({
url: 'js/xml/Menue.xml',
dataType: 'xml',
success: function(data) {
alert(data);
returnVal = data;
},
error: loadfail
});
return returnVal;
}
and test the return value with
alert(initXML());
The first alertBox has a value, but the second alertBox is empty. What is wrong?
Thanks!
You won't get any data on this alert(initXML())
because the function initXml
has an asynchronous request, at the time the alert fires, the function initXML
returns undefined
. You will alert something for the alert(data)
though.
If you want to see the value of returnVal
in an alert only after the async request is done, add this to your AJAX settings:
complete: function(jqXHR, textStatus){
alert(returnVal);
}
Also, my two side notes:
console.log()
instead of alert
if you are debugging. There are few things more embarassing than alerts that pop up in production code.success
, error
, and complete
have been deprecated (see https://api.jquery.com/jQuery.ajax/)