0

How i can get array after function ajax. I know that it is possible async false but this not good.what should I do?

var visit_time=[];
    var phrase=[];
    $.ajax({
       url: "https://api-metrika.yandex.ru/stat/sources/phrases.json",
       data: {
          id: "111111",
          pretty: "1",
          oauth_token: "code_token"
       },
       dataType: "jsonp",
       success: function(data) {

                var str = "";
                var len = data.data.length

                for (var i = 0; i < len; i++) {
                    visit_time.push(data.data[i].visit_time);
                    phrase.push(data.data[i].phrase)
                }

            alert(phrase)
       }

    });

    //get visit_time and phrase
ZKolya
  • 135
  • 7

2 Answers2

-1

You can execute a callback after a ajax request is successful.

function callback(arr) {
    // do something with the array 
    console.log(arr);
}
success: function(data) {

  var str = "";
  var len = data.data.length

  for (var i = 0; i < len; i++) {
    visit_time.push(data.data[i].visit_time);
    phrase.push(data.data[i].phrase)
  }

  callback(data);
}

You can also use the idea of a Promise.

   var visit_time=[];
    var phrase=[];

        function callback(arr) {
              alert(arr)
              console.log(arr);
            }

    $.ajax({
       url: "https://api-metrika.yandex.ru/stat/sources/phrases.json",
       data: {
          id: "11111",
          pretty: "1",
          oauth_token: "token"
       },
       dataType: "jsonp",

       success: function(data) {

                var str = "";
                var len = data.data.length

                for (var i = 0; i < len; i++) {
                    visit_time.push(data.data[i].visit_time);
                    phrase.push(data.data[i].phrase)
                }

             callback(phrase); // You have access here
       }

    });
     callback(phrase); // cannot access it as AJAX is asynchronous.
Sushanth --
  • 55,259
  • 9
  • 66
  • 105
-1

Due to the asynchronous nature of AJAX requests, if you want to handle the response you absolutely have to place said code inside the callback function:

success: function(data){
    // Only this code will have access to the response data. 
}

You might consider splitting your code into functions and calling those functions from the success callback.

Zoon
  • 1,068
  • 2
  • 11
  • 26