Jump to content

ajax to change src of iframe


brown2005

Recommended Posts

I'm not sure if it's possible to reload an iframe or not.  However, one thing you could probably do is to add a div tag to every iframe that you have.  You might be able to put the ajax code in the "parent" page and then have it refresh the content inside of the div tag in the iframe.  Of course, the ENTIRE content of the iframe would just need to be contained inside of that div tag.

 

Try putting this javascript into your parent page:

 

<script type="text/javascript">
var xmlhttp;

function reloadIframe(page)
{
  xmlhttp=GetXmlHttpObject();
  if (xmlhttp==null)
  {
    alert ("Sorry but your browser does not support AJAX or Javascript has been disabled");
    return;
  }

  // append an random value to the page being called
  // to prevent browser caching
  var url = page + "?id=" + Math.random();


  // execute the fully formed request
  xmlhttp.onreadystatechange=stateChanged;
  xmlhttp.open("GET",url,true);
  xmlhttp.send(null);
}


function stateChanged()
{
  if (xmlhttp.readyState==4)
  {
    document.getElementById("iframeContent").innerHTML=xmlhttp.responseText;
  }
}


function GetXmlHttpObject()
{
  if (window.XMLHttpRequest)
  {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    return new XMLHttpRequest();
  }
  if (window.ActiveXObject)
  {
    // code for IE6, IE5
    return new ActiveXObject("Microsoft.XMLHTTP");
  }
  return null;
}
</script>

 

In this example all you have to do is put a div tag with the id "iframeContent" in your iframe page (let's call it foo.php) like this:

 

<?php
  echo "<div id=\"iframeContent\">\n";

  // the page content goes here

  echo "</div>\n";
?>

 

 

Then your button should invoke the javascript function with the name of the target page.  Something like:

 

echo "<a href=\"javascript:reloadIframe('foo.php')\"><img src=...></a>\n";

 

Does that work?  I dunno...I don't mess with iframes usually.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.