Efe
Efe

Reputation: 954

Declaring global variable

I know that this question has been asked million times so my apologies.

I looked at all other examples and I dont understand why the following code is not working now.

I get undefined alert box when I place it outside the CheckinMap function.

Why is it?

$(document).ready(function() { 
    var MapData;
        $(function CheckinMap() {
                $.ajax({
                    type: "GET",
                    url: "content/home/index.cs.asp?Process=ViewCheckinMap",
                    success: function (data) {
                        MapData = data;
                    },
                    error: function (data) {
                        $("#checkinmap").append(data);
                    }
                });
            });
    alert(MapData);
    }); 

Upvotes: 0

Views: 318

Answers (2)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123428

MapData is undefined because the alert is executed while the ajax call is still running (ajax is asynchronous) and the response is not yet available. So change your code in this way

 success: function (data) {
         MapData = data;
         alert(MapData);
 },

or continue the code execution calling another function

 success: function (data) {
         continueExecution(data)
 },
 ...

 function continueExecution(data) {
     alert(data)
 }

or use deferred objects (on jQuery 1.5+)

$.ajax({
   type: "GET",
   url: "content/home/index.cs.asp?Process=ViewCheckinMap"
})
.done(function(data) { alert(data) })

Upvotes: 7

THD
THD

Reputation: 1

The execution order is asynchronous. Currently the following steps are executed:

  1. Ajax call
  2. alert(MapData); // unknown
  3. success function that sets MapData (or the error function that doesn't even set MapData)

You could alert in the success function (like suggested), but then you don't know if the variable is local to that function or is actually global. To test if MapData is actually global you can use setTimeout to alert the variable back.

Check out this modified example code:

// Global variable
var MapData;

// Global function
function test() {
  alert(MapData);   
}

$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "http://www.google.nl",
        success: function (data) {
            MapData = data;

            // Call global function with timeout
            setTimeout(test, 10);
        },
        error: function (data) {
            $("#checkinmap").append(data);

            // Set error message instead of data (for testing)            
            MapData = 'error';

            // Call global function with timeout
            setTimeout(test, 10);
        }
    });
});

Or you can test it out here: http://jsfiddle.net/x9rXU/

Upvotes: 0

Related Questions