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.

1

2 Answers 2

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);
});
Sign up to request clarification or add additional context in comments.

Comments

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;

}

1 Comment

@DBK please reffer this link stackoverflow.com/questions/6517403/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.