Press "Enter" to skip to content

XML Parsing With PHP And jQuery…Continued

As in my previous post I gave an idea of Xml and its parsing, In continuation with the last post here I will try to explain how XML and JQuery works.

When an AJAX request is sent to the server, we receive a response from server it may be either success or a failure. In case of success we get data in Xml or other format. In case of XML we can parse it by Jquery.
For Example: We posted an AJAX request to fetch all records of employees from database and display on page.


type: “POST”,  //type of request  GET or POST
url: emp_detail.php, // url to which the request is send
success: function(xmlData){// function to be called if the request succeeds
funEmpData(xmlData); // return data
error: function(){  //function to be called if the request fail



This Ajax request retrieve all detail of employee, I use Mysql and PHP to get it. Let we have a database table having columns user_id, username and address.  In file ‘emp_detail.php’ we retrieve data and create Xml.


// Connection to MySql
$conn = mysql_connect(‘localhost’,’root’,”);
// Selecting Database
$sql = "select * from emp";
$results = mysql_query($sql);
$count = 0;
$return_data = ”;
// Creating xml
while ( $row = mysql_fetch_assoc($results))
$xml_node      .= "<emp_data>\n";
$xml_node     .= "<userid>" . $row[‘user_id’] . "</userid>\n";
$xml_node     .= "<username>" .$row[‘username’] . "</username>\n";
$xml_node     .= "<address>" . $row[‘address’] . "</address>\n";
$xml_node     .= "</emp_data>\n";

$returnXML = "<?xml version=’1.0′ encoding=’UTF-8′?>\n".$xml_node;

echo $returnXML;


Above code give Xml when Ajax request is processed and create  ‘emp_data’ as a parent node and userid, username and address as a child node


<?xml version=’1.0′ encoding=’UTF-8′?>


We get this Xml in success of an Ajax request in variable ‘xmlData’, and to parse this Xml we create a function funEmpData.


function funEmpData(xmlData)
// all raw data is in returnXML
// itertin through loop in jQuery
var table_data = ‘<table border=1 ><tr><td>User Name</td><td>Address</td>’;

var username    = $(this).find(‘username’).text();
var address     = $(this).find(‘address’).text();
table_data += ‘<tr >’;
table_data += ‘<td>’+username+'</td>’;
table_data += ‘<td>’+address+'</td></tr>’;


table_data += ‘</table>’;

$(‘#emp_search_data’).html(table_data); // for display


In above function, to display employee detail we embedded data in Html table structure. Looping through Xml,  Jquery first find parent node and get all nodes one by one and all data is embed in Html table and at the end display that data in DIV having id  ‘emp_search_data’.

One Comment

  1. m
    m May 3, 2014

    Wonderful write up. Well done.

Leave a Reply

Your email address will not be published. Required fields are marked *