0

I need to pass y variable values to global array. Ajax can take json object data perfectly.

var data = [],
  totalPoints = 10;

function getRandomData() {

  if (data.length > 0) {
    data = data.slice(1);
  }
  // Do a random walk

  while (data.length < totalPoints) {
    var y;

    $.ajax({
      url: 'phpHelperDoc/get_live_data.php',
      type: 'POST',
      data: {
        authentication: "SN0000000004"
      },
      global: false,
      async: false,
      success: function(msgy) {
        var day_data = JSON.parse(msgy);
        y = day_data['value_1_live'];
        //Need to send this y value to var data=[];
      }
    });
    data.push(y);
  }
}
Nimantha
  • 6,405
  • 6
  • 28
  • 69
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Taplar Sep 17 '20 at 18:54
  • move data.push(y); in your success handler – gaetanoM Sep 17 '20 at 19:02
  • if i move to success handler browser is not responding, i am using var data[] for update live graph. then i change var y; to var y=50, it updates 50 in the graph. :( – Pasan Shanaka Sep 17 '20 at 19:07

3 Answers3

0

You just need to put the line

data.push(y); 

inside the success function. If that doesn't work. Ajax has also a complete function that is executed when the ajax call is completed try copying the code from success into the complete.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Zinah NA
  • 46
  • 3
  • if i move to success handler browser is not responding, i am using var data[] for update live graph. then i change var y; to var y=50, it updates 50 in the graph. :( – Pasan Shanaka Sep 17 '20 at 19:13
  • since you are in a while loop try setting async: true, in the ajax call – Zinah NA Sep 17 '20 at 20:48
0

Your data array is not greater than zero, therefore, your logic won't work.

replace:

if (data.length > 0) 

with:

if (data.length >= 0) 

An empty array length is Zero.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Adesoft
  • 305
  • 3
  • 3
0

There are a few ways to accomplish that with a pull, a call, or a bind. Or you can use a global function(). But, let me explain the problem first and a function solution.

When you call $.ajax({...}); any return value stays within the scope of the function. To overcome this. Create a function on the global scope to push the new values to the array and call the function from within the success call.

 // build an array to populate 
    var data = [];
    
    // create a function to push the value into array
    function hoistArrayReturn(arg){
     data.push(arg);
    } 
    
    // call function when data is retrieved
    $.ajax({
       ...
       success: function(msgy) {
         var day_data = JSON.parse(msgy);
         hoistArrayReturn(day_data); // will make it available outside the $.ajax call
        }
       ...
    });
Sergio Rodriguez
  • 8,258
  • 3
  • 18
  • 25