Higeath Higeath - 6 months ago 12
JSON Question

Getting data from PHP with AJAX for the first time

So i simply use this updateData function to get values from my php file it works after the first interval, but I would like to get first data after the page loads so I've tried doing var

var dataset=[];
updateData();


Before the intervals starts but dataset is still not updated immidiately I get empty array []

function updateData(){
$.ajax({
type: 'POST',
url: 'parser.php',
dataType: 'json',
cache: false,
success: function(result) {
dataset = result;
},
});

}
<?php
$datasetJSON = array();

for($i=0;$i<7;$i++){
$datasetJSON[] = rand(1,1000);
}
echo json_encode($datasetJSON);
?>

Answer

I think your problem is understanding that AJAX is not synced!

That means your code will keep running and not wait for the AJAX call to return. You could think of AJAX calls as threads that will run seperately of your main thread.

  var dataset=[];
  updateData();
  console.log(dataset); // will execute immediately!
  function updateData(){
      $.ajax({
              type: 'POST',
              url: 'parser.php',
              dataType: 'json',
              cache: false,
              success: function(result) {
                  dataset = result;
                  console.log(dataset); // now it's updated
              },
      });
  }

You could call AJAX synced:

  var dataset=[];
  updateData();
  console.log(dataset); // now it's updated
  function updateData(){
      $.ajax({
              type: 'POST',
              url: 'parser.php',
              dataType: 'json',
              cache: false,
              async: false, // <-- This will sync the AJAX call (and freeze the browser)
              success: function(result) {
                  dataset = result;
                  console.log(dataset); // now it's updated
              },
      });
  }

However, it defeats the purpose of AJAX. You should learn how the deal with callback functions.