Replace iframe with div AJAX

Published: Sunday, August 24, 2014

Tags: AJAX web

The iframe was originally used for displaying a web page inside another. When the internet bandwidth is limited, it could be useful to only update a partial content without reloading other elements. It worked well in the old days when JavaScript was suffering from compatibility issue, since no JavaScript is required. For example,

<iframe src="example.htm" name="iframe1"></iframe> <p><a href="" target="iframe1">Link</a></p>

However, it might be difficult to update the content of parent frame from inside an iframe, or to have more interactivity between the pages.

div and AJAX

AJAX is exactly designed for updating parts of a web page without reloading the whole page. The ideal of using XML is more efficient and simplifies data exchange scripts. Just define a div and have JavaScript do the work (remember to set asynchronous parameter of the open method to 'true'):

<div id="content"></div>
<p><a href="javascript:" onClick="changeCont();">Link</a></p>
function changeCont() {
    var xmlhttp;
    var x;
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        xmlDoc = xmlhttp.responseXML;
        x = xmlDoc.getElementsByTagName("content");
        document.getElementById("changeCont").innerHTML = x[0].childNodes[0].nodeValue;
    }"GET","new_content.xml", true);