Image gallery from Mysql with Ajax
Posted: Wed Jan 24, 2007 10:34 pm
Hi, I am trying to build an image gallery from some image data stored in a mysql databse using Ajax. I have a small thumbnail of these images and when clicked I would like to have the bigger size picture to be displayed, without having to reload the whole page using Ajax. I have the following HTML code in my thumbnails:
To simplify my code lets assume the following:
The 6 is the ID in the database corresponding to that image.
This is my JavaScript code (summarized for easier understanding):
And finally here is my php code which is supposed to display the image from the database (show_largePicture.php):
If I try show_largePicture.php?picture=5 alone it works ok, I can see the image that's stored in my database, but If I try it using the thumbnails with Ajax, it just doesn't work, it displays a few weird characters (I guess is the image data).
Any ideas on what I may be doing wrong? Is it even possible to do it?
Thanks!
P.S. I hope I posted this in the right forum section since it has three different programming languages...
Code: Select all
<img onClick="show_picture('6');" src="my_thumb.jpg">To simplify my code lets assume the following:
The 6 is the ID in the database corresponding to that image.
This is my JavaScript code (summarized for easier understanding):
Code: Select all
function show_picture(picture){
xmlHttp=GetXmlHttpObject()
var url="show_largePicture.php"
url=url+"?picture"+picture
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function stateChanged() {
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
document.getElementById("Divpicture").innerHTML=xmlHttp.responseText //The "Divpicture" is a DIV inside my HTML document
}
}
function GetXmlHttpObject(){
var objXMLHttp=null
if (window.XMLHttpRequest){
objXMLHttp=new XMLHttpRequest()
}
else if (window.ActiveXObject){
objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
}
return objXMLHttp
}And finally here is my php code which is supposed to display the image from the database (show_largePicture.php):
Code: Select all
<?php
$picture=$_REQUEST["picture"];
$table_name ="images";
$img_field = "b_imagedata";
$mime_field = "c_type";
include_once("../scripts/connect.php"); //This connects to MySQL database
$sqlQuery = "SELECT ".$img_field.",".$mime_field." FROM ".$table_name." WHERE i_imagen= ".$picture;
$sqlResult= mysql_query ($sqlQuery,$db);
$data = mysql_fetch_array($sqlResult);
mysql_close($db);
header("Content-Type: ".$data[$mime_field]);
echo $data[$img_field];
}
?>Any ideas on what I may be doing wrong? Is it even possible to do it?
Thanks!
P.S. I hope I posted this in the right forum section since it has three different programming languages...