Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

jQuery $.each for $.getJSON | Not being able to grab values from multidimensional array

I want my jQuery code to do the same as my PHP code provided at the bottom, but after 1.5 days, I havent found any helpfull information.

<script>
  $(document).ready(function(){
    var studNt = $.getJSON('http://127.0.0.1/includes/klradGetNt.php/');
    studNt = studNt.emp
    studNt = studNt.id1;
    $.each(studNt.stud, function (key, value){
      // alert("student id: "+ value +".");
    });
  });
</script>

var studNt retrieves

{
  "emp": {
    "id1": {
      "stud": [
        "1",
        "7"
      ]
    },
    "id2": {
      "stud": [
        "5"
      ]
    }
  }
}

The code I have written in PHP works fine to do what I need it to do.
after getting the Json file this is what I want it to do but in jQuery:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$data[] = array();
$data = file_get_contents("http://127.0.0.1/includes/klradGetNt.php/");
$data = json_decode($data, true);

foreach ($data['emp']['id1']['stud'] as $key => $value){
    echo 'student: '. $value .'. ';
}

What php returns:

student: 1. student: 7.

I have also read other posts throughout the days, but still I don’t under stand.

Any help in the right direction is much appreciated and thanks!

>Solution :

The structure returned from the AJAX call is an object, not an array. This may be why your research efforts didn’t find an answer.

The equivalent JS code to the PHP you’ve displayed would access the object (and the child objects in its properties) by key and then use a forEach() loop over the stud array, like this:

studNt.emp.id1.stud.forEach(value => console.log(`student: ${value}`);

Also note that you need to put any logic which depends on the response of an AJAX request (as used in $.getJSON()), to be placed in the callback argument, or chained from the jqXHR object returned from $.getJSON().

With that said, your full code block should look something like this:

jQuery($ => {
  $.getJSON('http://127.0.0.1/includes/klradGetNt.php/', studNt => {
    studNt.emp.id1.stud.forEach(value => {
      console.log(`student: ${value}`);
    })
  });
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading