Here we are going to look into how to return JSON data from PHP to ajax function of JQuery.
Return JSON data from
PHP to AJAX function of JQuery
Here we are going to look into how to return JSON date from PHP
script to AJAX function of JQuery. I think already you are familiar
with PHP and AJAX function of JQuery . If not, I suggest understanding them
first before reading this article.
As we are returning JSON data from PHP script, I hope
you have basic understanding of JSON too.
A small introduction of JSON: JSON stands for
XML. We can create JSON data in any programming language (almost all any web
programming language like asp,php and jsp etc) .
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
Let’s try this procedure step by step. As we are using PHP
script , to run this example you have to configure Apache server in your
system. I would recommend you to use XAMPP (for windows) to configure apache
and try this example.
Step 1) Configure apache and keep below code in your HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
// Code using $ as
usual goes here.
As we are using ajax function , we have to give JQuery
plugin in our program. This article uses JQuery plugin from Google’s CDN. So if you
want to same CDN , make sure internet is working in your system otherwise you
may download Jquery plug-in and host in your system.
Step 2) Add below code
in PHP file.
$rows = array("result" => 'This is JSON data');
$json = json_encode($rows);
This PHP code is very simple , simple
JSON data is created and using echo $json; statement JSON data will get displayed and will
return to ajax function of JQuery.
Here is sample output.
This is simple example to return JSON data from PHP script. If you want dynamic data you may use database to generate JSON data.