Jump to content

Could PHP pass images via ajax to javascript?


D.Rattansingh

Recommended Posts

I've been doing some work on generating some diagrams and midway through I decided to have php generate them as images (when in the past I would have used css and javascript). I'm almost completed this work however I'm now wondering if PHP could pass these generated images to javascript via ajax to be displayed in some div which is as a result that this part of my design uses ajax.

Link to comment
Share on other sites

in general, browsers directly request the images that are displayed on a page via the url of that image. you can use javascript/ajax to write/update the html on a page that would then cause an image to be displayed/refreshed. the image itself can be dynamically produced and output by php on the server. there would be no need for actual ajax to do this (making an async http request to get changing html from the server), just use javascript to 'write' the <img src url into the DOM of the page to get the browser to request the image from the server.

 

do you have a more detailed statement or example of what you are trying to accomplish?

Link to comment
Share on other sites

It involves a lot of mathematical calculations in which I decided to create a lot of diagrams.

 

For the first few I had to do, I created them with php using css for the formatting and since for those sections I'm using ajax, it's pretty easy to send back the html code to javascript to execute and display.

 

The idea crossed my mind to use images instead of divs and css and did a lot of work on it. But since those sections are already designed to use ajax I'm wondering if the image created could be passed.

 

 

So in the page there is are divs, when the user clicks a search button they get filled up with charts and formatted data by calling to javascript which then calls to php via ajax. But now there is an image involved which is not saved but rather created "on the fly". Once it gets to javascript it's easy to push it into the innerHTML of the html page. I have not tried it yet, just wondering if it's possible since the only way I communicate with php back to javascript is using the echo statement.

Link to comment
Share on other sites

What mac_gyver was getting at is that you can just call the PHP script from the image tag directly, there is no need to save the image to a file on the server. Just have your JS add a new image tag to the DOM like so:

var img = document.createElement('img');
img.src = 'generate.php?param=value&param2=value2&etc=etc';
document.body.appendChild(img);
You add whatever data the script needs to generate the graphs as URL parameters and then just have the script generate and output the image.

 

As for the actual question "Can you pass an image back with ajax?" the answer is yes, as a data: uri. For example you might send back a json response looking like:

{
   "status": "up"
   , "icon": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAAZiS0dEAHQA/wBxbIuINwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sBFBYIBm8nX8sAAAAdaVRYdENvbW1lbnQAAAAAAENyZWF0ZWQgd2l0aCBHSU1QZC5lBwAAAfVJREFUOMudk01oE1EUhc/MZEzSSpupTaFWMYsaNCDWQZGxS39WxZ+6KCLiRrrowpWLgujCnSLuLEQQRHEjXbkRpRQpKW6kBJQYKja1xJBmZkrHmTdvZt78uJBIaOMieavH5dyPc899D+jyTBauHAYArlvAbXOGmg2rzHfTfKN0/Wl8bzxBdPKmYweXP15KHpRHSMCCYG5fXox1CkhKiSVGGaet6R8AoKMRLi5MHANw0lIJ7C17CgA6chBFWHRND3Tb/vZu4r3V1sHYo7EL7ZrPz5+bdgw6SA0KarhTzfq/EI/ey/UHflAhqiWlR9M3i7PFl62A8efjHs/zYhiE28u3lqVmnQeA7Gz2tFbRtfVPPyWjZkGvbL2Qn8hnmiIlr7wmDUukBgWj7G4r+G8GEXqZzQSPMIR+BH094MSe2JKSV4aiMIK+pl/jBR48ZV7pQWmuFcADwOrD1cWh7KAycCgV+q4Px3RR+1IX1O/qhlH7XbBUwlHTBTjM78xGaF70gv4rM5l5C2CaaITzvQBEtfdYGklHERCyIEodkE7VF+pBK2DXS5Qfy0c2Ple/aj80AeAQS8QQT4qQMqli9Vn1xE79rjWu3FkpjxwfHu0b7vOBCL7jw7Fc9Az0Xm233v/+hdz93P7NcqPAHD+e7E+UN1/Vz7bT/QE+w9rOepXa4QAAAABJRU5ErkJggg=="
}
Doing something like that takes up a lot of unnecessary bandwidth however as data URI's get pretty big. You're better off going the dynamic image route as mentioned previously.
Link to comment
Share on other sites

Here's a simple working example. Two files, one to display and the other to create the GD image

 

display_bar.html

<html>
<head>
<script type='text/javascript'>
    function setSrc(v)
    {
        imgobj = document.getElementById("im");
        imgobj.src = "img_bar.php?max=100&val="+v;
    }
</script>
</head>
<body>
<div style="background-color: black; padding: 25px; text-align: center;">
    <img src="img_bar.php?max=100&val=0" id="im" />
</div>
<br>
Set bar percentage
<br>
<input type='button' name='btn1' value='40' onclick="setSrc(this.value);">
<input type='button' name='btn2' value='60' onclick="setSrc(this.value);">
<input type='button' name='btn3' value='80' onclick="setSrc(this.value);">
</body>
</html>

img_bar.php

<?php
/***************************
* Simple bar image
* Author : Barand
****************************/
$im = imagecreatetruecolor(200,20);
$bg = imagecolorallocate($im, 0xff,0x00,0x00);
$bar = imagecolorallocate($im, 0x00,0xFF,0x00);
$blk = imagecolorallocate($im, 0x00,0x00,0x00);

$val = $_GET['val'];
$max = $_GET['max'];
$x = $max ? $val * imagesx($im) / $max : 0;
imagefill($im,0,0,$bg);
imagefilledrectangle($im,0,0,$x,imagesy($im),$bar);


header("content-type: image/png");
imagepng($im);
imagedestroy($im);
?>

Edited by Barand
Link to comment
Share on other sites

I've run into a problem, hope you could give some assistance.
 
I got through with passing the images to javascript and my code looked similar to yours, this is the call: 

document.getElementById("img3").src="ajax.php?area=" +encodeURIComponent(area);

This is working fine but I have a few lines after which I want to execute after the image is loading and there seems to be a timing problem since the lines are executing before the image is being loaded

 

What I would have done in the past with ajax would be create an object of XMLHttpRequest(), send the request, wait for the message and after execute my code with the use of XMLHttpRequest.readyState == 4)

 

I tried doing it like that but wasn't working so decided to go with the above. Is there a way to determine when the call has been completed? i.e. the image finished loading?

Edited by D.Rattansingh
Link to comment
Share on other sites

Can it be done with javascript?

 

I tried using my normal ajax code in my javascript file but it didn't work, it's as follows:

ar = new XMLHttpRequest();
if(ar.readyState == 4 || ar.readyState == 0)
{
     ar.open("GET", "ajax.php?area=" +encodeURIComponent(area), true);
     ar.send(null);
     ar.onreadystatechange = function()
     {
          if(ar.readyState == 4)
          {
               document.getElementById("img3").src = ar.response;
          }// end if
     }// end function
}// end if

Any ideas on what is wrong with this? If I get this way to work it will solve my problem since I can put my code in the if(ar.readystate==4) block. I suspect something is wrong with the line

document.getElementById("img3").src = ar.response;
Edited by D.Rattansingh
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.