Sending XML Requests

Although the objects we’ve been creating are called XMLHttpRequest objects, so far we have made absolutely no use of XML. This is where the term “Ajax” is a bit of a misnomer, because the technology actually allows you to request any type of textual data, with XML being just one option. As you have seen, we have requested an entire HTML document via Ajax, but we could equally have asked for a text page, a string or number, or even spreadsheet data.

So, let’s modify the previous example document and PHP program to fetch some XML data. To do this, take a look at the PHP program first: xmlget.php, shown in Example 17-6.

Example 17-6. xmlget.php
<?php
if (isset($_GET['url'])) {
    header('Content-Type: text/xml');
    echo file_get_contents("http://".sanitizeString($_GET['url']));
}

function sanitizeString($var) {
    $var = strip_tags($var);
    $var = htmlentities($var);
    return stripslashes($var);
}
?>

This program has been very slightly modified (the changes are shown in bold) to first output the correct XML header before returning a fetched document. No checking is done here, as it is assumed the calling Ajax will request an actual XML document.

Now on to the HTML document, xmlget.html, shown in Example 17-7.

Example 17-7. xmlget.html
<html><head><title>Ajax XML Example</title>
</head><body>
<h2>Loading XML content into a DIV</h2>
<div id='info'>This sentence will be replaced</div>
<script>

nocache = "&nocache=" + Math.random() * 1000000
url = "rss.news.yahoo.com/rss/topstories" ...

Get Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.