0

I have found the issue however my solution does not work. The variables d0 and d1 get populated but after the code creates and splices the array storelocations. Therefore, I get an error that d0 and d1 is undefined. Any solutions?

Javascript:

    $(function () {


        $.get("/Map/GetJsonData", function (data) {
            storeLocations = [];
            var d0 = data[0].Delay;
            var d1 = data[1].Delay;


        });

        var storeLocations = new Array();
        storeLocations.splice(storeLocations.length, 0, d0);
        storeLocations.splice(storeLocations.length - 1, 0, d1);


}
user2138160
  • 279
  • 1
  • 5
  • 14

2 Answers2

1

AJAX is asynchronous, either create a callback or do what you need to inside the AJAX callback:

$.get("/Map/GetJsonData", function (data) {
        storeLocations = [];
        var d0 = data[0].Delay;
        var d1 = data[1].Delay;

        var storeLocations = new Array();
        storeLocations.splice(storeLocations.length, 0, d0);
        storeLocations.splice(storeLocations.length - 1, 0, d1);
});
tymeJV
  • 103,943
  • 14
  • 161
  • 157
1

Since you are declaring your variables (d0 and d1) within the callback function of the $.get method, those variables are private and only accessible within that function after the line that they are declared on. Therefore, you should just move the storeLocations code into the callback function.

 $(function () {


    var storeLocations = new Array();
    $.get("/Map/GetJsonData", function (data) {
        storeLocations = [];
        var d0 = data[0];
        var d1 = data[1];


        storeLocations.splice(storeLocations.length, 0, d0);
        storeLocations.splice(storeLocations.length - 1, 0, d1);

    });
});

In my example, I declared storeLocations outside the scope of the $.get method, therefore it will be accessible anywhere within the jQuery document ready method scope (after the line that it was declared on).

MDiesel
  • 2,647
  • 12
  • 14