Retrieve & display image from database - using AJAX[POST
Hey all,
I'm kinda stuck on this. My situation: I have a MySQL database with a table where I store images (the file name, the mimetype of every file and the binary data in a BLOB plus a unique ID). Now what I'd like to achieve is to load an image from the database using AJAX and the POST method. Viewing a specific image using the GET method is quite simple, I just set the SRC attribute of an <img /> HTML tag to link to the PHP file and set the correct GET variables, there's no AJAX needed for that.
So the idea again, simplified: I click a button or something, and 'behind the scenes' PHP is retrieving an image from the MySQL database, depending on the unique ID that was provided by AJAX through the POST method. AJAX uses the returned data to fill an element somewhere in the document, and that would be the freshly-loaded image.
Alright here's some code:
-
//PHP retrieving an image:
$returnImageQuery = "SELECT imageName, mimetype, imageBinaryData FROM imageTable WHERE ID = $_POST['someID']";
$return = mysql_query($returnImageQuery );
$file = mysql_fetch_array($return );
$fileName = $file['imageName'];
$fileType = $file['mimetype'];
$fileBinaryData= $file['imageBinaryData '];
header("content-disposition: inline; filename=$fileName");
header("content-type: $fileType");
header('content-length: ' .strlen($fileBinaryData));
echo $fileBinaryData;
That's the PHP file that should collect the image data from the database. This actually works when I use a POST-method HTML form to specify the unique ID, but then I end up viewing the PHP file itself, and that's not quite what I want. But the PHP works, it's at least something.
Here's my javascript code that
doesn't work (I'm using jQuery by the way):
-
$('#some_area')
.click(
function(){
var ID = 7;
$.post(
'the_php_file_above.php',
{
someID : ID
},
function(data){
$('#element_to_insert_image')
.html('<img>' + data + '</img>);
}
);
}
);
Okay I know the
.html('<img>' + data + '</img>) part is never going to work, but I have absolutely no idea how to pull this one off.
Heeeelp!
-H