stevenpepe
stevenpepe

Reputation: 267

Testing JSON with PHP

JSON newbie trying to get a grasp on this. My page is not alerting anything. What is wrong here?

The name of this page is test.php.

<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>test</TITLE>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>


</HEAD>

<?php 

 $arr = array ('item1'=>"test1",'item2'=>"test2",'item3'=>"test3");      
 $test = json_encode($arr);
 echo $test;

?>

$(function() { 
   $.getJSON('test.php',function(data) {   

    alert("Testing Data Item1 , its value is: >" + data.item1 + "<"); 

           $.each(data,function(i, item) {     
    alert(item.key);       
            });    
        }); 
    });  
</script> 

Upvotes: 0

Views: 1934

Answers (1)

prodigitalson
prodigitalson

Reputation: 60413

You need to remove the HTML from the page outputting the JSON. All you want in test.php is:

<?php 
 $arr = array ('item1'=>"test1",'item2'=>"test2",'item3'=>"test3");      
 $test = json_encode($arr);
 echo $test;
?>

The one thing i usually do though is also explicitly set the content type header:

<?php 
 header('Content-type: application/json');
 $arr = array ('item1'=>"test1",'item2'=>"test2",'item3'=>"test3");      
 $test = json_encode($arr);
 echo $test;

?>

Upvotes: 1

Related Questions