Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through JSON Array

I have a JSON array that I'm passing to PHP. Eventually I'll be passing and receiving alot more from my PHP file but for the moment this is it. Right now it's recieving 1 array and sending back that same array, no problem. I can loop through the data in Javascript but how do I loop through the array I pass to my PHP file? I get errors with foreach and a for loop didn't seem to help any. Suggestions?

Javascript

var fullName = ["John Doe", "Jane Doe"];

$(window).load(function(){
    getList();
});

function getList(){
    $.getJSON(
        "names.php",
        {names : JSON.stringify(fullName)},
        function(data) 
        {
            for(var i = 0; i < data.test.length; i++)
            {
                window.alert(data.test[i]);
            }
        }
      );
}

PHP

<?php
    $names=json_decode($_REQUEST['names']);

foreach($names as $name)
{
    echo $name;
}

    $data['test'] = $names;
    echo json_encode($data);

The foreach errors out on the foreach line telling me "Warning: Invalid argument supplied for foreach()"

like image 403
Howdy_McGee Avatar asked May 11 '26 15:05

Howdy_McGee


1 Answers

json_decode() doesn't return an array. To get it to do so you'd need to do json_decode($_REQUEST['names'], true)

http://php.net/manual/en/function.json-decode.php

like image 144
James C Avatar answered May 14 '26 04:05

James C