How to display jpeg as original attribute of IMG tag returned by PHP file using jQuery

I have to admit that as a neophyte, I don't even know how to ask my question. Here goes though.

Context: I have a script entry written in PHP that uses a security code that generates a PHP script that generates a jpeg that is loaded directly as an image containing a graphical representation of a randomly generated string that is stored in a cookie and needs to be entered by the registering party for confirmation of the registration form.

Purpose: I want to create my own "updated" code that will call the security code generating the script to create and display a new security image every time I click the "Refresh" button.

Here is the security code generating the script:

<?php

$im = imagecreate(300,60) or die("Cannot initialize new GD Image stream"); // identyfikator zasobu
$backgroundcolor = imagecolorallocate( $im, 225, 225, 225 );
$textcolor = imagecolorallocate( $im, 0, 0, 0 );
imagefilledrectangle($im, 0, 0, 140, 30, $backgroundcolor);


if( isset($_POST['refresh']) )
{
    if( isset($_COOKIE['randomimage']) )
        unset($_COOKIE['randomimage']);

    $randomizedString = createRandomString();
    imagestring( $im, 100, 65, 20, $randomizedString, $textcolor );
    setcookie('randomimage', $randomizedString, time() + 270 );
}
else if ( !isset($_COOKIE['randomimage'] ) )
{
    $randomizedString = createRandomString();
    imagestring( $im, 100, 65, 20, $randomizedString, $textcolor );

    setcookie('randomimage', $randomizedString, time() + 270 );
}
else
{
    $image_string = $_COOKIE['randomimage'];
    imagestring( $im, 100, 65, 20, $image_string, $textcolor );


}

header("Content-type: image/jpeg");
imagejpeg($im);
imagedestroy($im);


function createRandomString()
{
    srand( (double) microtime() * 1000000 );

    $letters_capital = range('A', 'Z');
    $letters_small = range('a', 'z');
    $number = range(0,9);

    $chars = array_merge($letters_capital, $number, $letters_small );

    shuffle($chars);

    $randString = "";

    for ( $i = 0; $i < 10; $i++ )
    {
        $randString .= $chars[$i] . " ";
    }

    return $randString;
}

      

? >

Here is the jQuery code, part of the registration script:

$('#refreshBtn').on('click', function(event){
        $.post(
            "./createrandomizedimaged83r04.php",           // action
            {                                   // data
               refresh: "refresh"
            },
            function(data)                      // callback
            {


                $('#imgPic2').attr('src',data);


            }
        );

    });

      

The result will appear in the firefox console as follows:

GET http://***directory***/%EF%BF%BD%EF%BF%BD%EF%BF%BD%EF%BF%BD 

      

At this point, I suspect, although I'm probably not using the correct terminology, I'm trying to nudge some kind of binary representation of the image into the img src, resulting in gibberish.

If instead, inside the jQuery part I write the following:

$('#imgPic').html('<img src=\'' + data +'\'>');

      

I am served the following:

     Yy?j  :U /6@ d  .z      O    0      3  7  ե\  |C-   D y ] h-ؑ)  #  ŏʼ  ~    4 m   *   ,  *H  ޭ 7  = 4  Y    w   p ;   8Pp0   rN   Ѵ{8       A{ _qh 1 }  ' cg{i ڥՕ 76 gd Hpy~    ' T    H U I ;מ nSa R J Ҧ t  ^I     % UcvU   gnH kѨxj x   :L J # ; ٝ   $     / %Oǿ    ] e^x   u    e  x  q  FFA9կ<   _ h   b      Z &   e @.0W 79    Q_ kJ   -!  c  bV@B0 AӥiQ\W    |k #N՞  YgI  9~HY7&  nO r s " }*      5   c  X  '*  f7  Ǩ (   (   (   (   (   (   (   (         mt 4 Ta| Wluc  y 袀3uh   >     * \ $ $ ,  I ޯAV G$Pġ# 5   `ڤ        ~ m L 4^la  G\ a  9  V o ١ g     g     ny L  Ps  A

      

How on earth do I take an image that is passed by a PHP script code generator and use jQuery to display it?

Here's where the image should go (inside the registration script):

<table align='left' border='0' cellspacing='0' cellpadding='4' width='100%'>
<tr>
    <td align='center' colspan='2' id='imgPic' name='imgPic'><img id='imgPic2' src='{$this->image_url}'></td>
</tr>
<tr>
    <td align='center' colspan='2' id='refreshBtn' name='refreshBtn'><input id='refreshBtn' name='refreshBtn' type='button' class='button' value='Refresh'></td>
</tr>
<tr align='center'>
    <td align='right' style='width:50%;'><span class='registration'><font style='color:#663300;'>Enter the above phrase:</font></span></td>
    <td align='left' style='width:50%;'><input type='text' id='wordVal' name='wordVal' autocompelte='off' maxlength='10' size='17'></td>
</tr>
<tr>
    <td align='center' colspan='2'><span id='orgWord'></span>
    <br>
    <span id='usrWord'></span></td>
</tr>

      

Please help me with the code. Also, since the jQuery code (inside the registration script) makes a POST request to the code generating script, I would like to know how to set the updated image using a POST request instead of a GET.

With respect and gratitude in advance.

+3


source to share


2 answers


If content-type

belongs to the image type itself, there is no need to open an ajax request:

$('#refreshBtn').on('click', function(event) {
    $('#imgPic').attr('src', './createrandomizedimaged83r04.php?_=' + (new Date()).getTime());
});

      

However, this is not a post request, as the tag img

opens a receive request by default.




If you really need to do this with a post request, I suggest you use an ajax request expecting base64 content.

Make your PHP script the result of a base64 image (check this post ) and use the result as an attribute src

like you do in your javascript.

+3


source


You can use data XMLHttpRequest()

or fetch()

to POST

for the server and get a response from the server as Blob

or ArrayBuffer

, which can be converted to Blob URL

or data URI

using FileReader

or Response

, then set the result as an .src

item <img>

.

jQuery.ajax()

and jQuery.post()

has no default option to install .responseType

on "blob"

or "arraybuffer"

; or call .blob()

or .arrayBuffer()

, see pdf view from arraybuffer file .



let url;

$('#refreshBtn').on('click', function(event) {
  if (url) {
    URL.revokeObjectURL(url);
  }
  var fd = new FormData();
  fd.append("request", "request");
  var request = new XMLHttpRequest();
  request.open("POST", "./createrandomizedimaged83r04.php", true);
  request.responseType = "blob";
  request.onload = function() {     
                     url = URL.createObjectURL(this.response);           
                     $('#imgPic2').attr('src', url);
                   }
  request.onerror = function(e) {
                      console.log(e, this.responseText)
                    }
  request.send(fd);

});

      

+2


source







All Articles