2
votes

At the moment I'm trying to use ajax to send objects via POST to be processed on the receiving end.

var studentString = JSON.stringify(studentArray);

console.log(studentString);

// process the form
$.ajax({
        type: 'POST',
        url: 'process.php',
        data: {'students': studentString}, 
        dataType: 'json', 
            encode: true
        })

The output after JSON.stringify is as follows, so everything would seem to be okay so far.

[{"name":"bob","gender":"m","level":"4","topic":"subtraction"},
 {"name":"john","gender":"f","level":"3","topic":"addition"}]

On the receiving end (php side) I'm trying to retrieve the data using json_decode, as follows:

$result = json_decode($_POST['students'], true);

However, after that I am at a loss. How can I loop through the resulting array to output the details on each student, one at a time? Or output (for example), the name of each student?? I've tried variations of

foreach ($result as $k => $value) { 
    $msg .= $k . " : " . $result[$k];    
}

...but I'm not having any luck. Any help would be appreciated.

2
What does var_dump($result); gives ? - Kevin Grosgojat
@Yonel has provided a good solution to your question. You might also want to look at the w3school php tutorial for simpler examples and explanation or better check out the php page. Hope this helps - Just Ice

2 Answers

2
votes

The $result is an array of elements, so try this:

foreach ($result as $data) { 
    echo $data['name']." : ".$data['gender']; //etc.   
}
0
votes

Try this:

   $.ajax({
        type: 'POST',
        url: 'process.php',
        data: {'students': studentString}
    })

process.php

foreach ($result as $k => $value) { 
    $msg = "name is:" . $value['name']; 
    $msg .=  ", gender is:" . $value['gender'];
    // add other 

    echo $msg."<br>";
}