Connecting to the server
In this example, we’re using the GET method, so we call the XMLHttpRequest object’s send method, passing it a value of null, which is JavaScript’s placeholder for a value of nothing.
The JavaScript code will be:
|
1 |
XMLHttpRequestObject.send(null); |
At this point we have created the XMLHttpRequest object, we opened it and we have created the connection to the server. From now we can make useful XML to store data and to have the source for our Ajax requests.
Using Ajax with XML
In the Firefox/Mozilla brand of browsers, we have to specify that we’re going to be downloading XML data, not plain text. To do that, we have to set the MIME type of the download to text/xml. We can achieve this using this line of code:
|
1 |
XMLHttpRequestObject.overrideMimeType("text/xml"); |
Another difference will be that we will use the XMLHttpRequest object’s responseXML property, which holds a JavaScript XML document object:
|
1 |
var xmlDocument = XMLHttpRequestObject.responseXML; |
Let’s say that we want to download data regarding streets name from a certain city area (Bucharest in my case). For this we have to create a variable streetsName which will hold the data parsed from the XML file ruled by the Tag Name read-only property:
|
1 |
streetsName = xmlDocument.getElementsByTagName("streetName"); |
After this we need to create the format for the placeholder of the data. In this case I will create a list of elements <span> displayed as block. Maybe it will be better to generate elements of an unordered list, but the problem is that, using the following sequence of JavaScript code, the HTML output will be a type of <ul></ul><li>...</li>, which means that we have an empty ul element and some orphans li elements, and this could lead to problems on CSS formatting.
The necessary code will be:
|
1 2 3 4 5 6 7 |
var xmlDocument = XMLHttpRequestObject.responseXML;
streetsName = xmlDocument.getElementsByTagName("streetName");
obj.innerHTML = "Here are the fetched streets name:";
for (loopindex = 0; loopIndex < streetsName.length; loopIndex++)
{
obj.innerHTML += "<span>" + streetsName[loopIndex].firstChild.data + "</span>";
} |
where obj = document.getElementById(divID); which is the container of our data.
The structure of the XML file will be simple:
|
1 2 3 4 5 6 7 8 9 10 |
<?xml version="1.0" ?>
<streetsName>
<streetName>Calea Victoriei</streetName>
<streetName>Regina Elisabeta</streetName>
<streetName>Lascar Catargiu</streetName>
<streetName>Iuliu Maniu</streetName>
<streetName>Cotroceni</streetName>
<streetName>Ion Ionescu de la Brad</streetName>
<streetName>Calea Dorobantilor</streetName>
</streetsName> |
From now the only thing we need to create is a form element which, based on user click action, will execute the function that will fetch the desired data from server.
The entire code (HTML and JavaScript) can be downloaded from the following link, a simple example on how data is fetched form server using Ajax and XML.






