nTuply nTuply - 23 days ago 16
JSON Question

Parse error with PHP json_encode

I'm getting an odd error and I'm not sure why it's happening. I'm trying to send multiple values to my ajax call which is resulting in

undefined
.

I tried to debug it and I realized that my PHP is getting a parse error with my
json_encode
. The reason seems to be with the passing of multiple values. Can anyone explain why is that so?

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

$files = glob("images/*.*");

for ($i=0; $i<count($files); $i++) {
$image = $files[$i];
}

echo json_encode("array_of_images" => $files, "size_of_array" => sizeof($files));
?>


Update: Ajax Code

<script>
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "img.php",
dataType: "html", //expect html to be returned
success: function(response){
alert(response.array_of_images);
alert(response.size_of_array);
},
error:function (xhr, ajaxOptions, thrownError){
// alert(thrownError);
}
});
</script>

Answer

The second value passed to json_encode should be options, not more data. You need to make your parameters into an array instead of passing it as 2 values:

 echo json_encode(array("array_of_images" => $files, "size_of_array" => sizeof($files)));
Comments