Forums / Craftwork / Client-side / [solved] Construct img tag with javascript and php

JonnyM
#12444 2009-05-14 01:13
Thx for your answers and @Koradhil, I actually tried that but it wouldn't load the image like that.
But after hours of searching I found an answer and will post it in case anyone else needs this.

Code you put in your HTML file:
<div id="mydivtag"><script type="text/javascript" src="http://www.mysite.com/myjavascriptfile.js"></script></div>

Code inside the .js file:
var xmlhttp
function getPHPtext()
{
xmlhttp=GetXmlHttpObject();

if (xmlhttp==null)
  {
  alert ("Your browser does not support AJAX!");
  return;
  }
  
var url="./the/path_to/phpfile.php";
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}

function stateChanged()
{
if (xmlhttp.readyState==4)
  {
  document.getElementById("mydivtag").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;
}

getPHPtext();

And finally, in the PHP file you can do whatever. Like get data from your database and then just echo it out. Anything the PHP file outputs through echo will be transfered through javascript to the HTML page. Even images and such.