How to bind a variable to a jQuery ajax request?

This is self-evident:

while (...) {
    var string='something that changes for each ajax request.';
    $.ajax({'type': 'GET','dataType': 'json', 'url': 'get_data.php'}).done(processData);
}
function processData(data) {
    // get string into here somehow.
}

As you can see, I need to somehow get stringin processData. I cannot create a global variable because it stringis different for every ajax request. So the question is, how do I bind stringajax to my request so that I can access it from processData?

I really do not need to add stringto the request and return the server, but if this is my only option, I have no choice.

Thanks in advance.

+3
source share
3 answers

try as follows:

while (...) {

    var str = 'something that changes for each ajax request.';

    (function(_str) {
        $.ajax({'type': 'GET','dataType': 'json', 'url': 'get_data.php'})
         .done(function(data) {
            processData(data, _str);
         });
    }(str));
}

function processData(data, str) {
  console.log(data, str);
}

and global variables were not used :)

+5
source
var string='something that changes for each ajax request.';
// Use a closure to make sure the string value is the right one.
(function() {
    // Store the "string" context
    var that = this;
    $.ajax({
        'type': 'GET',
        'dataType': 'json',
        'url': 'get_data.php'
    }).done(
        $.proxy( processData, that )
    );
}(string));

function processData( data ) {
    this.string === 'something that changes for each ajax request.' // true
}

$.proxy - jQuery (-) .bind().

, @Joel ( ), , .

+2
$(document).bind("ajaxSend",function(){
    $("#ajax_preloader").show();
}).bind("ajaxComplete",function(){
    $("#ajax_preloader").hide();
});
0

All Articles