1

I'm fetching data from database with php and mysql and returning an array with json that looks like this in the console :

enter image description here

I'm trying to iterate through this result in the success callback with this code without success :

$.ajax({
  type: 'POST',
  url: 'query/getUpdate.php',
  data: values,
  dataType: 'json',
  success: function(datas) {


    if (datas.message === 'success') {

      var selectedworkerid = datas.selectedworkerid;

      //display number of new messages

      datas = $.parseJSON(datas);
      $.each(datas, function(key, val) {
        console.log(key);
        console.log(val.selectedworkerid);
      });

    }

  }
});

What am I doing wrong or what I am missing for this to work?

5
  • if (datas.message === 'success') { is absolutely not trying to iterate... Commented Apr 29, 2019 at 20:30
  • 1
    datas does not have a message property: it is an array with objects. Those objects have the message property. Commented Apr 29, 2019 at 20:31
  • 2
    All your logic should be in the $.each(). You're trying to access elements too soon. Commented Apr 29, 2019 at 20:32
  • dataType:'json' means your "datas" (should be "data") has already been parsed, so you don't need to re-parse it with $.parseJSON. Put the $.each as the first line of the success callback and move the other code inside (and edit accordingly) - as others already said, you only have an array, "datas" itself doesn't have message/selectedworkerid. Commented Apr 29, 2019 at 20:37
  • 1
    datas in this context refers to an array of objects not a specific object inside that array. When you reassign datas it refers to the same array but as parsed JSON format so now you have the same data but in an official JSON format. Angel has it right. I took Angel's example and adapted it so you can see it in action: codepen.io/anon/pen/jRRKaa Commented Apr 29, 2019 at 20:56

1 Answer 1

1

You have to iterate over the objects in the array to be able to iterate over the key-value pairs of each object:

$.each(datas, function (index, obj) {
    if (obj.message === "success") {
        $.each(obj, function (key, val) {
            console.log(key);
            console.log(val);
        });
    }
});

To simply get the selectedworkerid of each object if the message is "success", you need to iterate once:

$.each(datas, function (index, obj) {
    if (obj.message === "success") {
        console.log(obj.selectedworkerid);
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.