user12882
user12882

Reputation: 4792

How to set a variable to a AJAX response data?

I am using jQuery and I have the following code:

var result = [];

if ( some_condition ) {
  result = [...]
} else {
  $.ajax({
    url:      some_url,
    data:     some_data,
    dataType: 'json',
    success:  function(data) {
      items = data
    }
  });

  result = items
}

// Playing with the 'result' variable...

The above code generates the error "items is not defined" when some_condition is false (I think it happens because the variable scope is not correct).

I would like to set the result variable to the AJAX response data but I don't know how to solve the problem.


Note: I am trying to do that because I would like to use the result variable outside the if ... else statement (that is, after the if ... else statement in the above code).

Upvotes: 5

Views: 24997

Answers (2)

Flavio
Flavio

Reputation: 398

Simply make the ajax function no async

var result = [];

if ( some_condition ) {
  result = [...]
} else {
    $.ajax({
    url:      some_url,
    data:     some_data,
    dataType: 'json',
    async: false, 
    success:  function(data) {
        items = data
    }
    });
   result = items
}

Upvotes: 12

Akhil Sekharan
Akhil Sekharan

Reputation: 12693

Do this:

Since you are calling it async, you should assign it in your callback function

var result = []; 


if ( some_condition ) {
  result = [...]
} else {
  $.ajax({
    url:      some_url,
    data:     some_data,
    dataType: 'json',
    success:  function(data) {
      result = data;
      validateResult(result);
    }
  });
}

And for your better understanding.

Your result array is a global variable.

  1. Initially its an array with length = 0;
  2. You call your ajax function.
  3. The length of result array is still 0.
  4. Ajax call completes and success function is executed.
  5. In success function you assign result to your response data.
  6. Now the length of result array is not zero any more .
  7. Globally the value is updated.
  8. You can use result array anywhere in your code

Upvotes: 3

Related Questions