0

I have an ajax request and I want to access an array defined in the ajax body outside its body.I am new to javascript so any help would be appriciated.This is my ajax request

 $.ajax({ 
             type:"GET",
             url: url , 
             success: function(finalresult) {
             arr=[]
             for(var i=0;i<finalresult.routes[0].geometry.coordinates.length;i++)
                        {
                        arr.push(finalresult.routes[0].geometry.coordinates[i])
                        global_data =arr.push

                                 }


                     }

               });

How can I access array arr outside the ajax body?

Miller
  • 135
  • 2
  • 12

1 Answers1

0

You can access it by creating a variable outside the ajax and setting its value inside the success function. Also note you can get its value only after the ajax & its success has finished its execution. For this you can use ajax done. Otherwise it is always going to give an empty array

let arr = [];
$.ajax({
  type: "GET",
  url: url,
  success: function(finalresult) {

    for (var i = 0; i < finalresult.routes[0].geometry.coordinates.length; i++) {
      arr.push(finalresult.routes[0].geometry.coordinates[i])
      global_data = arr.push

    }
  }
}).done(function() {
  console.log(arr)
});
brk
  • 48,835
  • 10
  • 56
  • 78