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:

$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!


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}`);
    })
  });
});