Question

This is self-explanatory:

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 get string into processData somehow. I can't make a global variable because string is different for every ajax request. So, the question is, how do I bind string to my ajax request so that I can access it from processData?

I really don't want to have to append string to the query and have the server return it, but if this is my only option, I have no choice.

Thanks in advance.

Was it helpful?

Solution

try in this way:

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 no global variables were used :)

OTHER TIPS

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 is the jQuery version (cross-browser) of .bind().

You could add an argument as @Joel suggested (in his deleted answer), but the less arguments the better.

$(document).bind("ajaxSend",function(){
    $("#ajax_preloader").show();
}).bind("ajaxComplete",function(){
    $("#ajax_preloader").hide();
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top