Joel Joel - 1 year ago 72
Javascript Question

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

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

Thanks in advance.

Answer Source

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

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

and no global variables were used :)