Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind variable to jquery ajax request?

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.

like image 248
Joel Avatar asked Feb 20 '23 09:02

Joel


2 Answers

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 :)

like image 131
Fabrizio Calderan Avatar answered Mar 05 '23 20:03

Fabrizio Calderan


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.

like image 35
Florian Margaine Avatar answered Mar 05 '23 20:03

Florian Margaine