Saturday, February 8, 2014

JQuery PHP & JSON

First, the JQuery function requests the PHP file for the data to be sent.
The server side code in PHP, requests the database for the data and gets the data.
Converts the received data into JSON format and sends it to the client side.
On the client side, JQuery (java script) receives the data in JSON format, extracts the required information, processes accordingly and displays in a table format.

Here in this example, the database connectivity is not included, rather, a JSON format is generated which is a question paper (objective type).

Client Side code: (index.html)
------------------
<html>
<head>
<script src="jquery/jquery-1.10.2.js"></script>
<script src="jquery_functions3.js"></script>
</head>
<body>
<p> Its working fine </p>
<table border='1' id="results"> </table>
</body>
</html>

Server Side code: (get_qp.php)
------------------
<?php
echo ' {"question_paper":
 [
{
"qid": "1",
"question": "Who is the father of computer?",
"opt1": "Charless Babbage",
"opt2": "Spider Man",
"opt3": "Professor X",
"opt4": "Robin Hood",
"answer": "a"
},
{
"qid": "2",
"question": "Who is the father of Java?",
"opt1": "Charless Babbage",
"opt2": "James Gauslin",
"opt3": "Professor X",
"opt4": "Robin Hood",
"answer": "b"
},
{
"qid": "3",
"question": "Who designed C Language?",
"opt1": "Charless Babbage",
"opt2": "Spider Man",
"opt3": "Dennis Ritchie",
"opt4": "Robin Hood",
"answer": "c"
}
]
 }
 ';

?>

JavaScript code (JQuery): (jquery_functions3.js)
--------------------------
$(document).ready(function()
{
   $.getJSON("get_qp.php",function(data)
   {
$.each(data.question_paper,function(i,qp)
{
var div_data = "<tr><td>"
+qp.qid+"</td><td colspan=4>"+qp.question+"</td></tr><tr><td></td><td><input type='radio' name='"+qp.qid+"'>"+qp.opt1+"</td><td><input type='radio' name='"+qp.qid+"'>"+qp.opt2+"</td><td><input type='radio' name='"+qp.qid+"'>"+qp.opt3+"</td><td><input type='radio' name='"+qp.qid+"'>"+qp.opt4+"</td></tr>";

$("#results").append(div_data);
});
  });
});

Points to remember before proceeding with execution:
-----------------------------------------------------
1. I used WAMP for the above code.
2. JQuery API should be downloaded and included if you dont want to use an online API.
3. Make sure that you are running an updated version on Java.
4. All the above three files are to be present in the same folder. If you want to keep the js file separately, then make sure that you do required modification in the html file.

Happy Coding.

Output:


No comments:

Post a Comment