0

I have an ajax request and I wanted to get the data and returned to whichever variable. So what I did is instantiate a temp variable and store the data there and later returning it. But whenever I return the value it turns out to be empty/undefined for some reason.

Here's my code:

function populateData(category, value, date, type){
  var tmp;
  $.ajax({
    url: 'php/populateChart.php',
    type: 'POST',
    data: 'type=' + type + "&date=" + date + "&year=" + today.getFullYear() + "&category=" + category + "&value=" + value,
    success: function(data, result) {
      console.log(JSON.parse(data));
      tmp = JSON.parse(data);
    },
    error: function(xhr, status, thrown) {
      console.log("ERROR: " + status + " THROW: " + thrown + " XHR: " + xhr.responseText);
    }
  });

  if (!tmp) {
    return "empty";
  } else {
    return tmp;
  }
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • The issue is because the AJAX request is *asynchronous*. See the duplicate I marked for more information. Also, as an aside, please don't provide `data` with an ugly long concatenated string. Use an object. – Rory McCrossan Aug 29 '17 at 09:06
  • 2
    Welcome to async world of javascript – Jocky Doe Aug 29 '17 at 09:07

0 Answers0