Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON AJAX - Return empty object [duplicate]

I'm using an AJAX call in a function to retrieve some data from the server, in this way:

getPolicies: function() {
  $.ajax({
    async: false, // wait for response
    type: "GET",
    url: "http://localhost:8080/getPolicies",
    contentType: "application/json",
    dataType: "json",
    success: function(jsonList) {
      for(var i in jsonList) {
        console.dir(jsonList[i].policyName);
      }
      return jsonList;
    },
    failure: function(err) {console.log("Error");}
  });
}

I correctly get the JSON array:

[ 
  { 
    "policyName": "policy1"
  },
  { 
    "policyName": "policy2"
  },
  { 
    "policyName": "policy3"
  }
]

This JSON array is returned by the function. But when I call the function getPolicies() I only get an empty JSON object {}. Specifically, if i try

var policies = getPolicies();
console.log(policies[1].policyName);

I get this:

Uncaught TypeError: Cannot read property 'policyName' of undefined

So, how is possible that even if I correctly get the JSON array, the function returns an empty object?! Thanks...

like image 320
Marco Avatar asked Jun 18 '26 07:06

Marco


1 Answers

Even though the AJAX request is synchronous *), the return statement still returns only from the success handler. Try something like this:

getPolicies: function() {
  // Declare variable here
  var resultList = null;

  $.ajax({
    async: false, // wait for response
    type: "GET",
    url: "http://localhost:8080/getPolicies",
    contentType: "application/json",
    dataType: "json",
    success: function(jsonList) {
      for(var i in jsonList) {
        console.dir(jsonList[i].policyName);
      }
      // Set the variable in the scope of getPolicies.
      resultList = jsonList;
    },
    failure: function(err) {console.log("Error");}
  });

  // This one actually returns getPolicies
  return resultList;
}

But in general, it's regarded bad practice to make AJAX calls synchronous. Instead, you can better call the necessary functionality from the success handler. That can also be another function. For instance, you can declare

function processPolicies(policies)
{
  console.log(policies[1].policyName);
}

And your call handler can look like this (:

$.ajax({
  async: true, // just let it run,
  type: "GET",
  url: "http://localhost:8080/getPolicies",
  contentType: "application/json",
  dataType: "json",
  success: function(jsonList) {
      processPolicies(jsonList);
  },
  ...

*) The first A even stands for Asynchronous. But on the other hand, the X stands for XML, so what you're doing here should actually be called JaJ rather than AJAX. ;)

like image 80
GolezTrol Avatar answered Jun 20 '26 21:06

GolezTrol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!