w3resource logo
Ajax Tutorial

Using Ajax with XML

Preface

In this tutorial, we will see how to send data to the server using XML and how data is retrieved from the server in the XML format. Since XML is widely used as a data format,it is worth learning how to send a request and receive a response using XML and Ajax. The following live demo shows you the end product we will create by the end of this tutorial. You supply data to a web form, that data is sent to the server using XML format, data is stored creating an XML file and then a response is received in XML format, to render data on the browser.

Send data to server

HTML code of our web form

For the sake of simplification, we have not added any validation in this form.

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="utf-8"> 
<title>Send request and receive response using XML</title> 
<meta name="description" content="HTML and JavaScript code of example of sending and receiving data using XML"> 
<link href="../includes/bootstrap.css" rel="stylesheet">
<style type="text/css">
body {padding-top: 40px; padding-left: 25%}
li {list-style: none; margin:5px 0 5px 0; color:#FF0000}
</style>
</head>
<body>
<form class="well-home span6 form-horizontal" name="xml-ajax" id="xml-ajax">
<div class="control-group">
              <label class="control-label" for="userid">Userid</label>
              <div class="controls">
                <input type="text" id="userid" placeholder="Required, 5 to 12 chars">
				<li id="msg1"></li>
              </div>
 </div>
 <div class="control-group">
              <label class="control-label" for="password">Password</label>
              <div class="controls">
                <input type="password" id="password" placeholder="Required, 7 to 12 chars">
				<li id="msg2"></li>
              </div>
 </div>
 <div class="control-group">
              <label class="control-label" for="name">Name</label>
              <div class="controls">
                <input type="text" id="name" placeholder="Required, alphabets & space only">
              </div>
 </div>
 <div class="control-group">
              <label class="control-label" for="country">Country</label>
              <div class="controls">
                <select class="span3">
                <option>INDIA</option>
                <option>USA</option>
                <option>UK</option>
                <option>CANADA</option>
                <option>FRANCE</option>
              </select>
              </div>
 </div> 
<div class="control-group">
              <label class="control-label" for="zip">ZIP Code</label>
              <div class="controls">
                <input type="text" id="zip" placeholder="Required, numeric & 6 chars">
              </div>
 </div>
 <div class="control-group">
              <label class="control-label" for="email">Email</label>
              <div class="controls">
                <input type="text" id="email" placeholder="Required">
              </div>
 </div>
 <div class="control-group">
              <label class="control-label" for="mfg">Gender</label>
              <div class="controls">
               <label class="checkbox inline">
  <input type="checkbox" id="inlineCheckbox1" value="option1"> Male
</label>
<label class="checkbox inline">
  <input type="checkbox" id="inlineCheckbox2" value="option2"> Female
</label>
              </div>
 </div>
 <div class="control-group">
              <label class="control-label" for="lang">Language</label>
              <div class="controls">
                <label class="radio">
  <input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" checked>
  English
</label>
<label class="radio">
  <input type="radio" name="optionsRadios" id="optionsRadios2" value="option2">
  Non-English
</label>
              </div>
 </div>
<div class="control-group">
              <div class="controls">
                <button type="submit" class="tn tn-success">Submit</button>
              </div>
 </div>
</form>
</body>
</html>

Now we will add the JavaScript code to send data to the server in XML format.

function Endorser() {
  // collect data from web form
var userid, password, name, country, zip, email, xmlString, data; 
userid = document.getElementById("userid").value;
password = document.getElementById("password").value;
name = document.getElementById("name").value;
country = document.getElementById("country").value;
zip = document.getElementById("zip").value;
email = document.getElementById("email").value;

//creating XMLhttpRequest object
 var xhr;
	 if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

//creating the xml string
    xmlString = "<userinfo>" +
    "  <userid>" + escape(userid) + "</userid>" +
    "  <password>" + escape(password) + "</password>" +
    "  <name>" + escape(name) + "</name>" +
    "  <country>" + escape(country) + "</country>" +
    "  <zip>" + escape(zip) + "</zip>" +
    "  <email>" + escape(email) + "</email>" +
    "</userinfo>";

//alert(data);
  // Build the URL to connect to
  var url = "save-userinfo.php";

  // Open a connection to the server
  xhr.open("POST", url, true);

  // declaring that the data being sent is in XML format
  xhr.setRequestHeader("Content-Type", "text/xml");

  // Send the request
  xhr.send(xmlString);
}

And now we will attach this JavaScript code to the HTML file and also add the SendToServer() against onsubmit event of the form.

<form class="well-home span6 form-horizontal" name="xml-ajax" id="xml-ajax" onsubmit="SendToServer()">

Processing data on server

On the server side, save-userinfo.php file will collect data send thorough the Ajax request and then that data is saved in an XML file. Here is the PHP code:

<?php
//collect data send as XML 
$xml = file_get_contents('php://input');
//open a file handler with read and write permission
$fh = fopen('userinfo.xml', 'r+');
//writing XML string to the new file
fwrite($fh, $xml);
//closing the file handler
fclose($fh);
?>

Since data is sent as XML, we collect data using file_get_contents('php://input');. And then opening the file userinfo.xml, we wrote the XML content sent into it.

Retrieving data from server as XML

And now we will see how to retrieve data from the server as XML using Ajax. We will also see how to render that data in the browser. For that, we will create a button on the client side. Once users click on the button, the Ajax script associated will fetch data from an XML file on the server and then it will be rendered in the browser.

Live Demo

Click on the button and recent updates will be loaded asynchronously from recent-updates.xml file.

XML Code

<rss version="2.0">
<channel> 
    <title>w3resource.com recent updates</title>     
    <link>recent-updates.xml</link> 
    <description>w3resource.com recent updates.</description>
<item> 
    <title>Ajax Tutorial</title>     
    <link>http://www.w3resource.com/ajax/introduction.php</link> 
    <description>In this tutorial we will see how to make Ajax work with PHP and MySQL. We will create a small web application. In that, as soon as you start typing an alphabet in the given input field, a request goes to the PHP file via Ajax, a query is made to the MySQL table, it returns some results and then those results are fetched by Ajax and displayed.
	</description> 
</item>
<item> 
    <title>Working with Ajax, PHP and MySQL</title>     
    <link>http://www.w3resource.com/ajax/working-with-PHP-and-MySQL.php</link> 
    <description>This is the first tutorial of the series of Ajax tutorials which covers the introduction to Ajax. The tutorial will help you to get started with Ajax.
	</description> 
</item>
<item> 
    <title>JSON Schema Tutorial</title>     
    <link>http://www.w3resource.com/JSON/JSON-Schema.php</link> 
    <description>In this tutorial we will discuss JSON Schema, a proposed Internet draft defining a JSON media type (application/schema+json). Internet Engineering Task Force defines JSON Schema as follows:</description> 
</item>
<item> 
    <title>Create Responsive Image and Content Slider with Orbit</title>     
    <link>http://www.w3resource.com/zurb-foundation3/orbit.php</link> 
    <description>Orbit is a JavaScript Image and Content Slider from Zurb Foundation 3, to create image and content slider easily. This tutorial unfolds the nuances of using Orbit.
</description> 
</item>
<item> 
    <title>Create Modal or Popup Windows with Reveal</title>     
    <link>http://www.w3resource.com/zurb-foundation3/reveal.php</link> 
    <description>You may create Modal or Popup Windows using Reveal - A Jquery Plugin form Zurb Foundaiton 3. In this tutorial, we will see how to use Reveal.
</description> 
</item>
<item> 
    <title>Responsive Web Design with Twitter Bootstrap</title>     
    <link>http://www.w3resource.com/twitter-bootstrap/responsive-design.php</link> 
    <description>This tutorial is about how to apply responsive design feature into your web layout. And in the course, you will also learn about Responsive Web Design. With the proliferation of mobile devices, it has become almost unavoidable that you don't have a version of your website which users can view well when browsing through mobile devices. And Responsive Web Design is a very efficient way to serve the purpose.
</description> 
</item>
<item> 
    <title>Zurb Foundation 3 Navigation</title>     
    <link>http://www.w3resource.com/zurb-foundation3/navigation.php</link> 
    <description>In this tutorial you will see how to create Navigations with Zurb Foundation 3. The framework offers navigations for various context and they are capable to be rendered across various devices.
</description> 
</item>
<item> 
    <title>Creating text effects with CSS3 text-shadow</title>     
    <link>http://w3resource.com/gallery/css3/text-effects-with-css3-text-shadow-property/</link> 
    <description>With CSS3 text-shadow property, it is much more easier now to create text effects like glowing effect, blurring effect, outlining, flaming effect etc. This document shows how to create text effects with CSS3 text shadow property.
</description> 
</item>
<item> 
    <title>SQL question answer</title>     
    <link>http://www.w3resource.com/sql/question-answer.php</link> 
    <description>This document is a collection of questions with short and simple answers useful for learning sql as well as for interviews.
</description> 
</item>
<item> 
    <title>HTML5 embed element</title>     
    <link>http://www.w3resource.com/html5/embed-element.php</link> 
    <description>HTML5 embed element represents external non-HTML application or interactive content. A good example is, when embed element is used to represent a flash movie(SWF file).
</description> 
</item>
<item> 
    <title>PostgreSQL JOIN</title>     
    <link>http://w3resource.com/PostgreSQL/postgresql-join.php</link> 
    <description>The main concept which is focusing on a join is that, two or more data sets, when joined, combined there columns into a new set of rows, including each of the columns requested from each of the data sets.
</description> 
</item>
<item> 
    <title>Zurb Foundation 3 Forms</title>     
    <link>http://www.w3resource.com/zurb-foundation3/forms.php</link> 
    <description>In this tutorial you will see how to create Forms with Zurb Foundation 3. The way Forms can be created with Foundation 3, is versatile. Let's begin with a simple example.
</description> 
</item>
<item> 
    <title>Zurb Foundation 3 Buttons</title>     
    <link>http://www.w3resource.com/zurb-foundation3/buttons.php</link> 
    <description>In this tutorial you will see how to create Buttons with Zurb Foundation 3. Foundation 3 Buttons are easy to use and customize. 
</description> 
</item>
<item> 
    <title>Create multi-device layouts with Zurb Foundation 3 Grid</title>     
    <link>http://www.w3resource.com/zurb-foundation3/grid-to-create-multi-device-layout.php</link> 
    <description>In this tutorial you will see how to create multi-device layouts with Zurb Foundation 3 Grid. The Grid is 12 column. You may also nest Grids with this Grid system.
</description> 
</item>
<item> 
    <title>Introduction to Zurb Foundation 3</title>     
    <link>http://w3resource.com/zurb-foundation3/introduction.php</link> 
    <description>Zurb Foundation 3 is a responsive front-end framework to build web sites and apps fast. It has all the basic as 	 well as advanced features for rapid prototyping. In this document you will get an overview of what this framework may offer.
</description> 
</item>
<item> 
    <title>A Twitter Bootstrap based simple table generator</title>     
    <link>http://w3resource.com/gallery/javascript/a-twitter-bootstrap-based-simple-table-generator/</link> 
    <description>This gallery item presents a Twitter Bootstrap based simple table generator. If you are new to front end development, this may help you to understand how to create and manipulate DOM with JavaScript. For others, we hope that it may come handy when you need to create HTML tables quickly for your next project.</description> 
</item>
</channel>
</rss>

HTML and JavaScript Code

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="utf-8"> 
<title>Retrieve data from server as XML using Ajax</title> 
<meta name="description" content="HTML and JavaScript code of example of Retrieve data from server as XML using Ajax by w3resource"> 
<link href="../includes/bootstrap.css" rel="stylesheet">
<style type="text/css">
body {padding-top: 40px; padding-left: 25%}
li {list-style: none; margin:5px 0 5px 0; color:#FF0000}
</style>
</head>
<body>
<p><button class="btn btn-primary" data-toggle="button" id="w3r_button" onclick="show_updates('recent-updates.xml')">Get recent updates</button></p>
<div id="updates">
</div>
<script type="text/javascript">
function show_updates(url)
{
var xhr;
var output,w3r,w3,i;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xhr=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xhr=new ActiveXObject("Microsoft.XMLHTTP");
  }
xhr.onreadystatechange=function()
  {
  if (xhr.readyState==4 && xhr.status==200)
    {
    output="<div class='well'>";
    w3=xhr.responseXML.documentElement.getElementsByTagName("item");
    for (i=0;i<w3.length;i++)
      {
      w3r=w3[i].getElementsByTagName("title");
	  w3r1=w3[i].getElementsByTagName("link");
        {
        try
          {
		  output=output + "<p><a href=" + w3r1[0].firstChild.nodeValue + ">" + w3r[0].firstChild.nodeValue + "</a></p>";
          }
        catch (er)
          {
          output=output + "<p> </p>";
          }
        }
    w3r=w3[i].getElementsByTagName("description");
      {
        try
          {
          output=output + "<p>" + w3r[0].firstChild.nodeValue + "</p><hr>";
		 }
        catch (er)
          {
          output=output + "<p> </p>";
		}
        }
     }
     output=output + "</div>";
    document.getElementById('updates').innerHTML=output;
    }
  }
xhr.open("GET",url,true);
xhr.send();
}
</script>
</body>
</html>

We encourage you to play around with the code, speak your mind in our comment section and share this tutorial.