I am using JQuery $.ajax to loop through a set of JSON URLs and download results into an array. Some of the URLs return a 404 — which I’m handling & showing as a div message.
However, I can’t seem to pass the URL, more precisely it always only passes the last URL in the array.
I assume that’s because ajax is asynchronous and takes longer to complete, but I’m not sure how else to make sure only the current JSON url (or variable) is being shown on SUCCESS or ERROR
My Code:
// For every URL loop through 'baseitems' array
for (var i = 0; i < baseitems.length; i++) {
// This is where I'm hoping to store the current URL as a variable to pass to the end-user on Success or Error
var caturl = baseURL + "/" + baseitems[i];
// Get the data via JSON
$.ajax({
type: "GET",
url: caturl,
dataType: "json",
async: true, // set so that the variables caturl get updated below
success: function (result) {
// Success: store the object into catalog array
cat.unshift(result);
$('#showdata').prepend("Loaded: " + caturl + "</br>"); // still buggy here - probably async JSON issue
},
error: function (xhr, textStatus, error) {
// Error: write out error
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
$('#showdata').prepend("ERROR : '" + error + "' trying to access: " + caturl + "</br>"); // still buggy here - probably async JSON issue
}
});
}
** UPDATE: WORKING CODE **
The completed working code with @charlietfl help + a few nice things like Success / Error code + count of URLs loaded is below. Thanks charlietfl & peacemaker!
$.ajax({
type: "GET",
url: caturl,
dataType: "json",
async: true, // set so that the variables caturl get updated below
beforeSend: function (jqXHR, settings) {
/* add url property and get value from settings (or from caturl)*/
jqXHR.url = settings.url;
},
success: function (result, textStatus, jqXHR) {
// Success: store the object into catalog array
var url = jqXHR.url;
cat.unshift(result);
$('#showdata').prepend("<font size=\"1\">Loading: " + url + " status: " + textStatus + "</font></br>");
successcount += 1;
},
/* error to be deprecated in jQuery 1.8 , superseded by "fail" */
error: function (jqXHR, textStatus, error) {
var url = jqXHR.url;
/* replace caturl with url in your append */
$('#showdata').prepend("<font size=\"1\" color=\"red\">ERROR : '" + error + "' trying to access: " + url + "</font></br>");
},
complete: function (jqXHR, textStatus) {
$('#showdata').prepend("<font size=\"3\">Loaded <b>" + successcount + "</b> of " + baseitems.length + " total catalogs.</font></br>")
}
});
Here is one way. The
beforeSendcallback option gives you access to both the jqXHR object and the ajax settings object.You won’t be able to use
caturlin the append of error, as it will not be in synch with the request throwing error.EDIT: based on 3rd party API comments, it is important to recognze following taken straight from $.ajax API