Search code examples
javascriptjquerymysqlimagesrc

Change image src without refreshing from mysql database


I am a bit of a pickle right now: I have an image displayed on my website, which has an src from a mysql server, it looks like this:

echo '<img src = "'.$sourceVariableFromDatabase.'" class = "profileImage" id = "profilePicture" />';

Also on my site, is a function that changes the database, and hence the value of $sourceVariableFromDatabase. However, the image won't update until the page is refreshed, but I would like it to display the new image src from the databse without refreshing.

I know this can be done through jQuery, but am unsure as to how to get the value from a database, as Javascript is not a server side, like javascript, and as far as I know cannot access databases in mysql.

How can I achieve this in Javascript/jquery.

Thanks, I have tried to be as clear as possible, and apologise for any waffle.


Solution

  • JQuery can be used to call a URL that returns data (e.g. HTML, JSON, text, etc). How that URL returns data can be however you want (PHP+MySQL, etc). Once JQuery receives the response, it can then update the img tag.

    Here is a simple example:

    Example HTML

    <img id="profilePicture" src="(your source from db1)" />
    

    Example JQuery on HTML page

    function update_image(db)
    {
      // get new image src
      $.get('some/url/to/get/new/src', {db: db}, function(response){
        // update the img src
        $('#profilePicture').attr('src', response);
      });
    }
    

    Example page (/some/url/to/get/new/src):

    <?php
    
    // get request data
    $db = $_GET['db'];
    
    // get img src
    $src = some_function_to_get_src($db);
    
    // output src
    echo $src;