Masey
Masey

Reputation: 17

Returning a variable within an ajax call

If I have the following ajax call (inside a function) how do I go about returning the 'test' variable, in this case a string for testing purposes? Currently i'm getting test is not defined.

function getMaps(){

    mapID = "us";

    $.ajax({
        type: "GET",
        url: "getMap.asp",
        data: "mapID=" + mapID,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        success: function(response) { 

            var test = 'text string';       
        }


      });
      return test;


};  

Upvotes: 0

Views: 192

Answers (3)

onder
onder

Reputation: 837

function getMaps(){

mapID = "us";
var test="";
$.ajax({
    type: "GET",
    url: "getMap.asp",
    data: "mapID=" + mapID,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    async: false,
    success: function(response) { 

        test = 'text string';       
    }


  });
  return test;

};

Upvotes: 1

zerkms
zerkms

Reputation: 255015

var right before test means that the variable will be visible only inside that anonymous function

Upvotes: 0

Vasiliy Kulakov
Vasiliy Kulakov

Reputation: 5491

Try to open a pop-up box or set the value of some text field instead. The response function you defined will get called asynchronously.

Also, "test" is not defined within the scope of the function from which it is returned. Move the definition to the top of that function -- it shouldn't be undefined, but it will still not solve the issue.

Upvotes: 0

Related Questions