Learn Javascript Tutorials, CSS Tutorials, HTML Tutorials and jQuery Tutorials

Learn CSS, HTML, JavaScript, jQuery and Ajax step by step from beginning to advance with examples and references. Apart from that, beginners can learn tricks and tips.more>>

Monday, October 6, 2008

Swap Images by XML using XMLHTTP Request

Calling XML file into HTML Page using XMLHTTP Request or ActiveXOject
Here, we have used some features for calling xml file into html document with the help of ajax. In the example mentioned below, we called xml nodes by using
item(0).firstChild.nodeValue

Below find the javascript code as a Example, as a result it shows toggle images effects.

Javascript file Source:

<script type="text/javascript">
function make()
{
var req;

if (window.XMLHttpRequest)
{
req = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
req = new ActiveXObject("Microsoft.XMLHTTP");
}

req.open("GET", "image.xml", true);
//req.load("ajax-get.xml");


req.onreadystatechange = function()
{
if(req.readyState == 4)
{
//alert(imgsrc);

var doc = req.responseXML;
var cont=document.getElementById("data");
var imgsrc=document.getElementById("pic");
var thumb=document.getElementById("pic_s");
var clickhere=document.getElementById("alink");

//var test = doc.getElementsByTagName('thumb');
var smallpic = doc.getElementsByTagName('thumb');
var lnkxml = doc.getElementsByTagName('link');

imgsrc.src = doc.getElementsByTagName('image').item(0).firstChild.nodeValue;
imgsrc.alt = doc.getElementsByTagName('alt').item(0).firstChild.nodeValue;
thumb.src = smallpic.item(0).firstChild.nodeValue;
clickhere.href = lnkxml.item(0).firstChild.nodeValue;


var rot=document.getElementById("spn1");
rot.innerHTML= smallpic.item(0).firstChild.nodeValue;

thumb.onclick=function()
{

//if(thumb.src==smallpic.item(1).firstChild.nodeValue)
if(rot.innerHTML==smallpic.item(1).firstChild.nodeValue)
{
imgsrc.src = doc.getElementsByTagName('image').item(0).firstChild.nodeValue;
imgsrc.alt = doc.getElementsByTagName('alt').item(0).firstChild.nodeValue;
thumb.src = smallpic.item(0).firstChild.nodeValue;
clickhere.href = lnkxml.item(0).firstChild.nodeValue;

rot.innerHTML= smallpic.item(0).firstChild.nodeValue;
}
else
{
imgsrc.src = doc.getElementsByTagName('image').item(1).firstChild.nodeValue;
imgsrc.alt = doc.getElementsByTagName('alt').item(1).firstChild.nodeValue;
thumb.src = smallpic.item(1).firstChild.nodeValue;
clickhere.href = lnkxml.item(1).firstChild.nodeValue;

rot.innerHTML= smallpic.item(1).firstChild.nodeValue;
}
//alert(thumb.src);
};
}


};

/* else if(req.readyState<4)
{
shots.innerHTML="Loading...";
}*/
req.send(null);
}

</script>


XML file Source:

<?xml version="1.0"?>
<root>
<image>images/img-1.jpg</image>
<thumb>images/thumb-1.jpg</thumb>
<alt>XML</alt>
<link>http://javascript-guru.blogspot.com/search/label/ajax/</link>
<image>images/img-2.jpg</image>
<thumb>images/thumb-2.jpg</thumb>
<alt>Ajax</alt>
<link>http://javascript-guru.blogspot.com/</link>
</root>