zomboble zomboble - 1 year ago 59
Javascript Question

Download picture from database to display via JavaScript?

I am developing mobile applications, and I was thinking, if I need to download a picture from a server, I cannot actually run the PHP natively (I am using a PhoneGap type setup), so how could I download a picture from a database, run it though JavaScript and then display it to the user?

I would imagine something like:

  1. Ajax request,

  2. Return HTML string of binary data

  3. Do some stuff to that?


  1. Ajax request,

  2. Return a HTML string of reference to the picture, for example:
    In JavaScript, write something like
    document.write <img src="http://blahh/img/"+imagePath

I'm not sure what the best way to do this is.

Answer Source

To my mind, the simplest way to dynamically load external pictures is to get a JSON object from a PHP script containing the picture URL (like http://www.example.com/pictures/getPicture/YOUR_PICTURE_ID).

Server side

    $pictureUrl = 'http://example.com/pictures/picture.jpg'; //You can get it with a database query
    $pictureName = 'Foo';
    $pictureAltText = 'Bar';

    // You can do some stuff here.

    // At the end of the script, write result.
    echo json_encode(compact('pictureUrl', 'pictureName', 'pictureAltText'));

Client side

<script type="text/javascript">
    // With jQuery
    $.getJSON('http://www.example.com/pictures/getPicture/YOUR_PICTURE_ID', function(data){
        console.log(data.pictureUrl, data.pictureName, pictureAltText);

        var img = new Image();
        img.src = data.pictureUrl;
        img.setAttribute('alt', data.pictureAltText);

        img.onload = function(){
            // Displaying picture when download completed

If you don't use jQuery, you have to use XMLHttpRequest to get the JSON encoded response and to parse it (you can see the MDN documentation at https://developer.mozilla.org/en-US/docs/JSON).