Dino Babu
Dino Babu

Reputation: 5809

JS Ajax function not setting variable value

I have a simple ajax function

  function get_country(request_term) {
    var country_list = '';
    $.ajax({
      url   : "activity/get_country", 
      type  : "POST",
      cache : false,
      data  : {
        request_term : request_term
      },
      success : function(data) {
        if(data != '') {
          country_list = $.parseJSON(data);
          alert(country_list);               ----> Got value here
        }
      }
    });
    alert(country_list);                     ----> Not getting value here
    return country_list;
  }

the problem is, i'm getting the data in the success function, but unable to return it from the main function.

Upvotes: 0

Views: 728

Answers (2)

user1969752
user1969752

Reputation:

You can do it by making async as false. But it is not a recommented way.

This code will return country_list

function get_country(request_term) {
var country_list = '';
$.ajax({
  url   : "activity/get_country", 
  type  : "POST",
  cache : false,
  async : false,
  data  : {
    request_term : request_term
  },
  success : function(data) {
    if(data != '') {
      country_list = $.parseJSON(data);
      alert(country_list);               
    }
  }
});
alert(country_list);                     
return country_list;

}

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191729

Because ajax is asynchronous, you can't know when the success function will complete (or if it will ever complete). Therefore any code that requires the result of the ajax call must depend on the ajax callback too.

jQuery makes it very easy to bind additional callbacks.

return $.ajax({ /* rest of your code */

get_country(request_term).done(function (data) {
    //are you sure JSON isn't returned already?
    country_list = $.parseJSON(data);
});

Upvotes: 1

Related Questions