Convert responseText to image

Discussion in 'JavaScript' started by bigtime, Jan 17, 2007.

  1. #1
    Hi,

    I'm trying to use ajax to display an image without refreshing the page.

    I use XMLHttpRequest() to post the request and use responseText to get the information from server. However, what I get is only some strings, so, how can I convert it to the image file?

    Here is my example page:

    http://www.memberscripts.com/php_new/login/reloadtest.php

    Here is the relevent part of my script:

    function sendRequest(act) { 
    
       // Open PHP script for requests 
       http.open('get', 'randomImage3.php'); 
       http.onreadystatechange = handleResponse; 
       http.send(null); 
    
    } 
    
    function handleResponse() { 
    
       if(http.readyState == 4 && http.status == 200){ 
    
          // Text returned FROM the PHP script 
          var response = http.responseText; 
    
          if(response) { 
             // UPDATE ajaxTest content 
             document.getElementById("randImage").innerHTML = response; 
          } 
    
       } 
       
     }
    PHP:
    randomImage3.php is a script that spits out a random captcha image.

    Thanks for any help!
     
    bigtime, Jan 17, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    Try
    
    document.getElementById("randImage").setAttribute('src', 'data:image/jpg;base64,'+ response);
    
    Code (Javascript):
    And send the image base64 encoded.
     
    nico_swd, Jan 17, 2007 IP
  3. ajsa52

    ajsa52 Well-Known Member

    Messages:
    3,426
    Likes Received:
    125
    Best Answers:
    0
    Trophy Points:
    160
    #3
    Try to send "Content-type: image/gif\n\n" (or jpg) on your php instead of "Content-type: text/html\r\n\r\n"

    It's how I'm doing on my signature site (although I'm using iframes instead of XMLHttpRequest objects).
     
    ajsa52, Jan 17, 2007 IP
  4. bigtime

    bigtime Peon

    Messages:
    226
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Hi,

    Thanks for both of your responses. I tried some different things and still no luck. Here is what I have in this file:
    http://www.memberscripts.com/php_new/login/reloadtest.php

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Untitled Document</title>
    <script language="JavaScript" type="text/javascript">
    
    function createRequestObject() { 
    
       var req; 
    
       if(window.XMLHttpRequest){ 
          // Firefox, Safari, Opera... 
          req = new XMLHttpRequest(); 
       } else if(window.ActiveXObject) { 
          // Internet Explorer 5+ 
          req = new ActiveXObject("Microsoft.XMLHTTP"); 
       } else { 
          // There is an error creating the object, 
          // just as an old browser is being used. 
          alert('Problem creating the XMLHttpRequest object'); 
       } 
    
       return req; 
    
    } 
    
    // Make the XMLHttpRequest object 
    var http = createRequestObject(); 
    
    function sendRequest(act) { 
    
       // Open PHP script for requests 
       http.open('get', 'randomImage3.php'); 
       http.onreadystatechange = handleResponse; 
       http.send(null); 
    
    } 
    
    function handleResponse() { 
    
       if(http.readyState == 4 && http.status == 200){ 
    
          // Text returned FROM the PHP script 
          var response = http.responseText; 
    
          if(response) { 
             // UPDATE ajaxTest content 
    		 
    		document.getElementById("randImage").setAttribute('src', 'data:image/jpg;base64,'+ response);
            document.getElementById("randImage").innerHTML = response; 
    		  
    
          } 
    
       } 
       
     }
    </script>
    </head>
    <body>
    <div id="randImage" align="center"><img src="randomImage3.php" alt="Verification Number" align="absmiddle" /></div>
    <input name="button" type="button" onclick="sendRequest('null');" value="New Code!" />
    </body>
    </html>
    
    PHP:
    Here is my randomImage3.php file:

    <?php
    session_start();
    
    // make a string with all the characters that we 
    // want to use as the verification code
    $alphanum  = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
    
    // generate the verication code 
    $rand = substr(str_shuffle($alphanum), 0, 5);
    
    // choose one of three background images
    $bgNum = rand(1, 3);
    
    // create an image object using the chosen background
    $image = imagecreatefromjpeg("background$bgNum.jpg");
    
    $textColor = imagecolorallocate ($image, 0, 0, 0); 
    
    // write the code on the background image
    imagestring ($image, 5, 5, 8,  $rand, $textColor); 
    	
    
    // create the hash for the verification code
    // and put it in the session
    $_SESSION['image_random_value'] = md5($rand);
    	
    // send several headers to make sure the image is not cached	
    // taken directly from the PHP Manual
    	
    // Date in the past 
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); 
    
    // always modified 
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 
    
    // HTTP/1.1 
    header("Cache-Control: no-store, no-cache, must-revalidate"); 
    header("Cache-Control: post-check=0, pre-check=0", false); 
    
    // HTTP/1.0 
    header("Pragma: no-cache"); 	
    
    
    // send the content type header so the image is displayed properly
    header('Content-type: image/jpeg');
    
    // send the image to the browser
    imagejpeg($image);
    
    // destroy the image to free up the memory
    imagedestroy($image);
    ?>
    PHP:
    Can you see what I'm doing wrong?

    Thanks!
     
    bigtime, Jan 17, 2007 IP
  5. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #5
    Actually, you don't need AJAX at all. You can do just:

    
    
    document.getElementById("randImage").setAttribute('src', 'randomImage3.php?r='+ Math.floor(Math.random() * 5000);
    
    
    Code (javascript):

    This would reload the image, and set a new session.
     
    nico_swd, Jan 17, 2007 IP
  6. bigtime

    bigtime Peon

    Messages:
    226
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #6
    So are you saying to do it like this?

       <img src="randomImage3.php" id='randImage' alt="Verification Number" align="absmiddle" /> 
    <input name="button" type="button" onclick="document.getElementById('randImage').setAttribute('src', 'randomImage3.php?r='+ Math.floor(Math.random() * 5000);" value="New Code!" /> 
    PHP:
    I tried that but it didn't do anything??

    Thanks,

    Tim
     
    bigtime, Jan 17, 2007 IP
  7. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #7
    I forgot a bracket.

    
    
    ...om() * 5000));"
    
    Code (markup):
     
    nico_swd, Jan 17, 2007 IP
  8. bigtime

    bigtime Peon

    Messages:
    226
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #8
    EXCELLENT! Thank you very much. Worked perfectly!

    Tim
     
    bigtime, Jan 17, 2007 IP
  9. jahmed

    jahmed Peon

    Messages:
    1
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #9
    Hi,
    I have a few buttons which are used to manipulate the image on the server. I am updating the src of the image to the url on the server.
    When the button is clicked in the javascript I am updating the cursor to wait using document.body.style.cursor = 'wait';
    now when the image is updated I want to change the cursor back to default document.body.style.cursor = 'default';
    How can I accomplish this. Would appreciate if someone could give a solution or sample code.
    Thanks,
    JA
     
    jahmed, Feb 24, 2011 IP