skip to Main Content

I receive a Json output from PHP page like this

[{"x":"2018-03-20","y":1,"z":7},{"x":"2018-03-22","y":31,"z":5},{"x":"2018-03-25","y":7,"z":21}]

How can I loop over the results so that I would have access to each of the elements? I have tried something like below but this does not seem to be working.

function LoadResultMorris()
{
$.ajax({
    type: "POST",
    url: 'admin/data.php',
    data: {type1: 'search1'},
    success: function(data){
$.each(data.data, function(key, value) {
    alert(data[key]);
    alert(data[value]);
});
        }
});

}

2

Answers


  1. Loop all list of objects in the following format

    $.each(JSON.parse(data.data), function(key,obj) {
       //Access Property in format Object.Atribute
       alert(obj.x); //X Atribute
       alert(obj.y); //Y Atribute
       alert(obj.z); //Z Atribute
    }); 
    
    Login or Signup to reply.
  2. Given that the data structure you’re working with is a plain array of objects, jQuery isn’t really necessary here. You can use a standard forEach() loop, accessing the properties of the object by name. Try this:

    // mock AJAX response:
    let data = [{"x":"2018-03-20","y":1,"z":7},{"x":"2018-03-22","y":31,"z":5},{"x":"2018-03-25","y":7,"z":21}];
    
    // inside the AJAX success handler:
    data.forEach(object => {
      console.log(object.x, object.y, object.z);
    });
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search