Drake
Drake

Reputation: 111

JQuery ajax request - global variable

So, I have this code:

$.post("contacts.php", 
    {zip: $("#zip").val()}, "json").done(function(data){
        var response = JSON.parse(data);
        $("#city").val(response[0].city);
        });}

It posts the zip code to the server, and the server returns the city name corresponding to the zip. Now the problem is, I want to access response[0].city outside of the done function. The problem is, I can't declare it as global. I tried to lose the var, I read that it declares it as global, but nop. Also tried to declare it as the first thing in my script, outside of any functions, still nop. It can't be accessed. I also tried to define a completly different variable as global, pass it the response variable to save it. Still nop.

Upvotes: 0

Views: 1125

Answers (1)

Omar Himada
Omar Himada

Reputation: 2588

I would use $.ajax instead of $.post so I can make it synchronous with async: false, then just create the variable before the $.ajax like this:

var city;

$.ajax({
    type: "POST",
    url: "contacts.php",
    data: { zip: $("#zip").val() },
    success: function(data) {
        var response = JSON.parse(data);
        city = response[0].city;
    },
    // by setting async: false the code after the 
    // $.ajax will not execute until it has completed
    async: false
});

// some operation with the city variable

NOTE: as of recently the usage of async: false is deprecated with jQuery and modern browsers. You should find a solution that does not involve using async: false.

Upvotes: 2

Related Questions