UPDATE: Based on suggestions here, I’ve modified my code. To get a handle on how this works, I am only trying to alert the PHP array with JSON. Still cannot get it to work. The code below resides on the same test.php page. If refreshed, should the alert fire? The function seems to fail as well. The TEST alert does not work.
<?php
header('Content-type: application/json');
$arr = array ('item1'=>"test1",'item2'=>"test2",'item3'=>"test3");
echo json_encode($arr);
?>
<script type="text/javascript">
$(function() {
$.getJSON('test.php',function(data) {
alert("TEST");
$.each(data, function(key, item) {
alert(key + item); });
});
});
});
</script>
I am new to JSON and trying to get a PHP array to display in an HTML file. Below is a simple example. Please tell me if this should work and what I am doing wrong. I am trying to output the keys in this array. Thanks.
My PHP script (test.php):
$arr = array ('item1'=>"test1",'item2'=>"test2",'item3'=>"test3");
json_encode($arr);
$content = file_get_contents('test.htm');
echo $content;
My HTML page (test.htm):
<script type="text/javascript">
$(function() {
$.getJSON('test.php',function(data) {
$.each(data,function(i, item) {
alert(item.key);
});
});
});
</script>
Make sure you have included jQuery in your HTML file.
As you are only alerting keys, you don’t have to wait for a dom-ready event – and even if you wanted to, I would first get the JSON and put the
$(function...into the ajax callback.Your JSON-encoded PHP-array should look like this:
Check about this in your debugger, or load test.php directly in your browser. As others have suggested, your PHP code with the
file_get_contentsis a bit odd.Last, your object traversal won’t work. Look at the docs:
The string concatenator in JavaScript is the
+, not the.as in PHP.item.keywould try to access thekeyproperty of one of your items – none has such one as thy are strings.