Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variable to function in jquery AJAX success callback

I am trying to preload some images with a jQuery AJAX call, but am having real problems passing a (url) string into a function within the success function of the AJAX call (if that makes sense).

Here is my code as is stands:

//preloader for images on gallery pages window.onload = function() {     setTimeout(function() {              var urls = ["./img/party/"]; //just one to get started          for ( var i = 0; i < urls.length; i++ ) {             $.ajax({                 url: urls[i],                 success: function(data,url) {                     $(data).find("a:contains(.jpg)").each(function(url) {                                                        new Image().src = url + $(this).attr("href");                     });                 }             });         };       }, 1000); }; 

One can see my (failed) attempt at passing the url through into the .each() call - url ends up takes the value of increasing integers. Not sure why or what these relate to, maybe the number of jpg files?

...anyway, it should of course take the single value in my original urls array.

Thanks for any help - I always seem to get in a bit of a twist with these callbacks.


PROGESS?

So, I mucked around a bit, taking heed of comments from @ron tornambe and @PiSquared and am currently here:

//preloader for images on gallery pages window.onload = function() {     var urls = ["./img/party/","./img/wedding/","./img/wedding/tree/"];      setTimeout(function() {         for ( var i = 0; i < urls.length; i++ ) {             $.ajax({                 url: urls[i],                 success: function(data) {                     image_link(data,i);                     function image_link(data, i) {                         $(data).find("a:contains(.jpg)").each(function(){                              console.log(i);                             new Image().src = urls[i] + $(this).attr("href");                         });                     }                 }             });         };       }, 1000);        }; 

I tried putting the image_link(data, i) here there and everywhere (in each nested function etc.) but I get the same result: the value for i is only ever logged as 3. I suspect that this is because all references to i point to the same thing and by the time the asynchronous task actually gets to image_link(data, i) the for... loop is over and done with (and hence has a value of 3). Needless to say this gives urls[i] as 'undefined'.

Any (more) tips how I can get round this?

like image 751
Jon Avatar asked Aug 24 '13 01:08

Jon


People also ask

What is passed to the callback function in an Ajax request?

The callback function is a function that is executed when the Ajax call is completed. The callback function is passed two parameters: the response from the Ajax call and the status of the Ajax call.

What triggers Ajax success?

AJAX success is a global event. Global events are triggered on the document to call any handlers who may be listening. The ajaxSuccess event is only called if the request is successful. It is essentially a type function that's called when a request proceeds.

What is success and error in Ajax?

jquery ajax calls are asynchronous by default. So success & error functions will be called when the ajax load is complete. But your return statement will be executed just after the ajax call is started.

What is function response in Ajax?

Response is the object passed as the first argument of all Ajax requests callbacks. This is a wrapper around the native xmlHttpRequest object. It normalizes cross-browser issues while adding support for JSON via the responseJSON and headerJSON properties.


1 Answers

Since the settings object is tied to that ajax call, you can simply add in the indexer as a custom property, which you can then access using this in the success callback:

//preloader for images on gallery pages window.onload = function() {     var urls = ["./img/party/","./img/wedding/","./img/wedding/tree/"];      setTimeout(function() {         for ( var i = 0; i < urls.length; i++ ) {             $.ajax({                 url: urls[i],                 indexValue: i,                 success: function(data) {                     image_link(data , this.indexValue);                      function image_link(data, i) {                         $(data).find("a:contains(.jpg)").each(function(){                              console.log(i);                             new Image().src = urls[i] + $(this).attr("href");                         });                     }                 }             });         };       }, 1000);        }; 

Edit: Adding in an updated JSFiddle example, as they seem to have changed how their ECHO endpoints work: https://jsfiddle.net/djujx97n/26/.

To understand how this works see the "context" field on the ajaxSettings object: http://api.jquery.com/jquery.ajax/, specifically this note:

"The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves."

like image 157
Paul Zaczkowski Avatar answered Oct 14 '22 14:10

Paul Zaczkowski