2

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 ? Commented Sep 5, 2016 at 15:57
  • @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 Commented Sep 5, 2016 at 16:08

2 Answers 2

2

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

foreach ($result as $data) { 
    echo $data['name']." : ".$data['gender']; //etc.   
}
Sign up to request clarification or add additional context in comments.

3 Comments

I've tried the above suggestion, but no result. var_dump($result) gives the following: [object Object],[object Object]
@mike I guess you try json_decode($_POST['students'], true);, note that the 2nd param true say that these objects will be converted into associative arrays.
Third time's a charm - json_decode($_POST['students'], true); gave me a result. Thank you for your help - it's very much appreciated.
0

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>";
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.