Florina Florina - 4 months ago 13x
SQL Question

How to use JS to display images from database

So I made a website that displays FPS information stored in a mysql database. For each second of gameplay I have a pair of number(fps)-image(screenshot).

I display the numbers in a line chart made with JavaScript. The behaviour desired is when I click on a bullet in the chart, the screenshot for that particular second is displayed in a div on the page.

I have to mention that the screenshots are stored in the database and they are very low in size. I display then using PHP like this:

$query = "SELECT `image` FROM `logs` WHERE `session_id`=".$_GET['session']." AND `second`=".$second;
$sth = $mysqli->query($query);
if (!empty($result))
echo ' <img id="screen" src="data:image/jpg;base64,'.base64_encode($result['image']).'"/>';

The method I'm using now is when I click on a bullet in the chart (action recorded in JS), I send it as a GET parameter and read it with PHP afterwards, like this:

window.location.href = url + "?second=" + second;

This method obviously will refresh my page. The problem is, the chart I made also has a zoom/scroll option and that resets whenever the page is refreshed, making the experience very bad for the user.

Is there any method to display the screenshots without refreshing the page, for this particular case (where I have to query the database for each click/picture)? Maybe there is a better way of approaching this problem?



I think you've got 2 solutions which are Ajax or Websocket depending your needs.

Ajax permit to asynchronously, only when you need, call the server and get datas from an URL which could be a webservice or PHP page... Perhaps, it's the better solution in your case.

To make it easy, you can use JQuery library by donwloading the script and insert it in your HTML :

<script src="jquery-3.0.0.min.js"></script>

To call the server, using JQuery :

    url: url + "/yourphppage.php",
    data: "parameter=" + yourOptionelParameter,
    async: false,
    success: function(data) {
    error: function() {
        alert("Your error");
    contentType: 'charset=utf-8'

Or if your prefer pure javascript.

Now, you just have to work on the presentation of your data, on the server side. It could be what you want HTML, TXT, JSON, XML...

Websocket is like a permanent tunnel opened between your server and the client. Each side can ask or send datas in real time.

It seems to be a library server side :
And client side, it's very easy :
Nice documentation on mozilla website

Hope it helps. Good luck.