0

i have this javascript code for accessing a JSON. There is a variable v1 that i declared global, but i can't access it outside this function.

    $.ajax({
            type: 'GET',
            url: url,
            async: true,
            jsonpCallback: 'jsonCallback',
            contentType: "application/json",
            dataType: 'jsonp',
            success: function(json) {
                //console.log("good");
                v1 = [];
                $.each(json, function(key, val) {
                   // $('ul').append('<li id="' + key + '">' + val.dir + ' ' + val.nr  + '</li>');
                   if(val.dir === "IESIRE"){
                      // console.log(val.data);
                       v1.push(val.data);
                   }
                });
            },
            error: function(e) {
                console.log(e.message);
            }
        });

    console.log(v1);

Please help to understand this.

Vlad Dev
  • 1
  • 1
  • 3
  • Sorry thanks for directions, found answer here: http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call – Vlad Dev Jun 18 '15 at 14:00

2 Answers2

0

You can get the data by a function call. You can read more about this here. An example fiddle http://jsfiddle.net/y4vv6t8y/

$.ajax({
            type: 'GET',
            url: 'http://echo.jsontest.com/key/value/one/two',
            async: true,
            jsonpCallback: 'jsonCallback',
            contentType: "application/json",
            dataType: 'jsonp',
            success: function(json) {
                //console.log("good");
                v1 = [];
                $.each(json, function(key, val) {

                       v1.push(val);

                });
                _callback(v1);
            },
            error: function(e) {
                console.log(e.message);
            }
        });
function _callback(data){
    console.log(data);
}
Community
  • 1
  • 1
meteor
  • 2,518
  • 4
  • 38
  • 52
0

Simply declare your variable var v1 = []; outside $.ajax call first. It will the be accessible from within the scope of the anonymous function you pass to $.each.

bitweiß
  • 11
  • 2