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 );
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.
var ID = 7;
someID : ID
.html(‘‘ + data + ‘);
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.
The easiest way by far to do this sort of content-in-a-database-type-thing is to create a url that returns image from a GET request. So it’s very similar to what you have already done, except use $_GET and get rid of the content-disposition header (you don’t need it).
Not quite sure why you are set on using POST to send an ID as it’s unnecessary. However, if you do need to use POST for some reason I suggest you post your details a PHP file that stores that information somewhere and returns a hash so that you can then supply in the src attribute ‘get_image.php?hash=zKJlkdsdkJF’. get_image.php would then look up the hash to get the ID and so.
Thanks for your reply. I am actually using that $_GET thingie right now, but I might just use your hash idea. It’s kind of a long story why I want this through $_POST, I”ll save you that. Was just wondering if I missed out on something while working my way through tutorials and help files.
One little other question – Do you happen to know whether it’s possible or not to upload a file using AJAX? I know about the iframe workaround, but is that as good as it gets?