1

I am trying to use the $.getJSON function to return data. I have the following html file named page.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<html xmlns=" http://www.w3.org/1999/xhtml ">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Request json test</title> 
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){

    $.getJSON("json-data.php",function(result){
     alert(result);
    });

  });

});
</script> 
</head>
<body>
<button>Get JSON data</button>
<div id="showdata"></div>
</body>
</html> 

I also have the following PHP file named json-data.php:

<?php
//request data from the database
//code here to connect to database and get the data you want

/* Example JSON format 
{
  "item1": "I love jquery4u",
  "item2": "You love jQuery4u",
  "item3": "We love jQuery4u"
}
*/
$item1 = "I love jquery4u";
$item2 = "You love jquery4u";
$item3 = "We love jquery4u";
//return in JSON format
echo "{";
echo "item1: ", json_encode($item1), "\n";
echo "item2: ", json_encode($item2), "\n";
echo "item3: ", json_encode($item3), "\n";
echo "}";
?>

I am only trying to use the alert function to see the data in the PHP file, however it does not work. Anyone know why?

Thanks, Jim

1
  • Response JSON format incorrect, do like that: echo 'item1: "', json_encode($item1), '"\n'; Commented Jun 7, 2012 at 20:38

1 Answer 1

1

It's because your json is in invalid format:

$items = array("item1" => "I love jquery4u", "item2" => "You love jquery4u", "item3" => "jquery4u");

echo json_encode($items);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.