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>