0

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.

Dino Babu
  • 5,814
  • 3
  • 24
  • 33
  • possible duplicate of [How to return AJAX response Text?](http://stackoverflow.com/questions/1225667/how-to-return-ajax-response-text) – Quentin Apr 12 '13 at 06:46

2 Answers2

1

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);
});
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
1

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;

}

  • @DBK please reffer this link http://stackoverflow.com/questions/6517403/what-are-the-drawbacks-of-using-synchronous-ajax-call –  Apr 12 '13 at 08:31