Galactic Civilizations 3
Retrieve data in Ajax and PHP in XML

Retrieve data in Ajax and PHP in XML

Category: Javascript.
Posted by on the 01/10/2013.
Last update on the 03/10/2013.

<<Previous tutorial    Next tutorial>>

Description

This tutorial explains how to use ajax in order to retrieve whenever you want the data sent by your PHP script in XML.

Introduction

This tutorial can be realized with a simple text editor like « Notepad ». This tutorial requires some basic knowledge in html, JavaScript and PHP and XML.

During this tutorial, we will modify the files created in the last tutorial. The modified files are:

  • ajax.js
  • server.php

The XML sent by the server is the following:

<?xml version="1.0" encoding="ISO-8859-1"?>
<series>
<val1>Value 1</val1>
<val2>Value 2</val2>
</series>

Script JavaScript

As we will retrieve the data in XML, we will use the responseXml attribut of the object XMLHttpRequest instead of the responseText attribut. To do that, change the function retrieveData of the file Ajax.js like this:

Ajax.js

...
if(req.status == 200){
/* We process the response */
processXML(req.responseXML);
}else{
...

As you can see, a new function has been created. This function is called processXML and as the name suggests, this function process the XML sent by the server by using DOM methods.

We can now add the processXML function:

Ajax.js

function processXML(data){
var processed;
processed = data.getElementsByTagName('val1')[0].firstChild.data;
processed += "\n"+data.getElementsByTagName('val2')[0].firstChild.data;
alert(processed);
}

In this tutorial, I explain how to retrieve the server response in XML format but we can also use ajax queries to retrieve the response as plain text.

Script PHP

Now, we can develop the PHP script on the server side. The script builds the XML described above and sends it to the client. To do that, replace the content of the PHP file by the one below:

server.php

<?php
$xml = '<?xml version="1.0" encoding="ISO-8859-1"?>';
$xml .= '<series>';
$xml .= '<val1>Value 1</val1>';
$xml .= '<val2>Value 2</val2>';
$xml .= '</series>';

/* We change the header. */
header('Content-type: text/xml');
echo $xml;
?>

Tests

This tutorial comes to his end, you can test your application by clicking on « ajax » button. The message : « Value 1 Value 2 » should be displayed.

AJAX XML

You like this tutorial ?
Like this website in order to promote it on facebook !

<<Previous tutorial    Next tutorial>>

You like this tutorial ? Share it with your friends !
Partager sur Facebook Partager sur Twitter Partager sur Myspace Partager sur Stumbleupon Soumettre sur Reddit Partager sur Digg Ajouter à vos favoris Technorati Ajouter à vos favoris Live Ajouter à vos favoris Google Ajouter sur vos favoris Yahoo