Grow your CSS skills. Land your dream job.

Retrieve & display image from database – using AJAX[POST]

  • # May 27, 2009 at 12:20 pm

    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:

    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):

    Code:
    $(‘#some_area’)
    .click(
    function(){
    var ID = 7;
    $.post(
    ‘the_php_file_above.php’,
    {
    someID : ID
    },
    function(data){
    $(‘#element_to_insert_image’)
    .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.

    Heeeelp! :mrgreen:

    -H

    # May 27, 2009 at 3:07 pm

    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).

    Say you called that file get_image.php – you could test the php code by browsing to http://www.example.com/get_image.php?imageID=1234 and the result should be an image displayed in the browser.

    The second challenge, which is integrating that image into a web page, can be done by manipulating the src attribute of an image tag on the page.

    $(‘#element_to_insert_image’).html(‘<img>’);
    $(‘#element_to_insert_image img’).attr(‘src’, ‘get_image.php?imageId=’ + someID);

    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.

    # May 27, 2009 at 5:12 pm

    Hi Dave,

    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?

    Thanks for the help.

    -H

    # May 27, 2009 at 6:53 pm

    Well I kind of guessed there might be more to it, so that’s why I posted my hash idea. Hope it works out for you.

    As for AJAX file uploads – I know GMail does that so it must be possible. I just googled this jQuery plugin – http://plugins.jquery.com/project/ajaxFileUpload never used it but it looks sweet!

    Cheers
    Dave

    # May 28, 2009 at 3:54 am

    YEa I’ve seen that one. But they use this workaround with the iframe. Might just use that eventually cause there doesn’t seem to be a non-iframe solution. Thanks a bunch for your help.

    # March 19, 2013 at 1:28 am

    Hi this is my short and simple solution:


    php:(up.ph)

    < ?php
    $link=mysql_connect("localhost", "user", "pass") or die (mysql_error());// server, user, pass
    mysql_select_db("images",$link);
    $id = $_REQUEST;
    $image = mysql_query($sql="SELECT thumb FROM pictures where id = $id");
    $image = mysql_fetch_assoc($image);
    $image=$image;
    echo base64_encode($image);
    mysql_close();
    ?>

    html + Javascript:


    -html-
    -head-
    -title--/title-
    -script src="jquery-1.9.0.js" type="text/javascript" charset="utf-8" --/script-
    -/head-
    -body-
    -img id = "imm" src="" alt="Red dot" /-
    -button onclick = "loadimage($('#picid').val())"-Click me!-/button--input type="text" id="picid" value="1" placeholder=""-
    -script type="text/javascript"-

    function loadimage(id) {
    $.ajax({
    async: false,
    url: 'up.php',
    type: 'POST',
    dataType: 'xml/html/script/json/jsonp',
    data: {
    id: id
    },
    beforeSend: function(){
    $('#imm').attr('src','ajax_loader.gif');
    },
    complete: function(data, xhr, textStatus) {
    //full solution read and change data:image/jpg from db
    $('#imm').attr('src','data:image/jpg;base64,' + data.responseText);
    },
    success: function(data, textStatus, xhr) {

    },
    error: function(xhr, textStatus, errorThrown) {}
    });
    }
    -/script-
    -/body-
    -/html-

    I think this good for you :)

Viewing 6 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".