Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing variables to jQuery ajax success or error functions

Tags:

json

jquery

ajax

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>")
                    }
                });
like image 493
NikG Avatar asked Jun 25 '12 22:06

NikG


1 Answers

Here is one way. The beforeSend callback option gives you access to both the jqXHR object and the ajax settings object.

You won't be able to use caturl in the append of error, as it will not be in synch with the request throwing error.

  $.ajax({
    /* url, data ...& other opts*/
    beforeSend:function( jqXHR, settings){
        /* add url property and get value from settings (or from caturl)*/
         jqXHR.url= settings.url;
   },
   /* 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("ERROR : '" + error + "' trying to access: " + url + "</br>");
   }

EDIT: based on 3rd party API comments, it is important to recognze following taken straight from $.ajax API

When data is retrieved from remote servers (which is only possible using the script or jsonp data types), the error callbacks and global events will never be fired.

like image 69
charlietfl Avatar answered Oct 22 '22 11:10

charlietfl