Return JSON data from PHP
Here we will use ajax function of JQuery to call PHP script and this PHP script will generate a simple JSON data. This JSON data will return to JavaScript method. Then we will parse returned data using JavaScript.
We are creating only two files first is index.php which contains jquery and html and then the request is sent to test.php
index.php (code)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>json</title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script> jQuery(document).ready(function($) { $("#testButton").click(function(e) { $.ajax({url:"test.php", type: "POST", dataType:"JSON", scriptCharset: "UTF-8", success:function(result){ alert(result[0].result2); } }); }); }); </script> </head> <body> <button type="button" id="testButton">Click me</button> </body> </html>
test.php
<?php $rows[] = array("result" => 'This is JSON data', "result2" => 'this is result 2', "result3" => 'this is result 3' ); $json = json_encode($rows); echo $json; ?>