skip to Main Content

I’m literally going crazy. I can’t figure out where is the error in the code below whose purpose is to retrieve an image from a database and display it in a frame with id ‘img1’. I’ve tried every way but what I get is just a string that isn’t transformed into an image. Some advice?

<?php

//file foto.php

include './admin/conn.php';

if (!empty($_POST['photo'])) {

 $Id = $_POST['photo'];

  $query=$conny->query("SELECT * from picture where cf ='$Id'");
        while($row=$query->fetch_array()) {
        
    echo $row["image"];
         
        }
} else {
        echo $searchErr = "Errore nell'estrapolazione del dato IN/OUT";
    } 
    
?>
//file index.php

 $.ajax( {
                                method: 'POST',
                                url: 'foto.php',
                                async: false,
                                data:{
                                    photo: data14      
                                    },
                                
                                success: function (result) {
                                    if (result != null && result != "") {
                                    
                                     
                        alert(result);   //<<<<<< (i get a JFIF string)
                                
        
document.getElementById("img1").src= '<img src="data:image/jpeg;base64, base64_encode('+result+') width="150px" height="150px" />';    //<<<<< (i get an empty frame)
                                                    
                                }}
                            })

2

Answers


  1. Chosen as BEST ANSWER

    I solved in this way:

    //in file foto.php
    
    echo base64_encode ($row["image"]);
    
     //in file index.php
    
    document.getElementById("img1").src = 'data:image/jpeg;base64, ' + result;  
    
    

    Thanks to all.


  2. That string is the image itself, you are just missing some details of how to show it.

    You say .src=; what follows should be what you want the src attribute to be set to, not an entire img tag. Though then you cannot set the width and height; you may want to modify your code to replace the image tag instead of just setting the src attribute if the rest of the img tag is not how you want it.

    And you seem to be trying to call the base64_encode php function in your javascript code; that doesn’t work like that. Use the btoa javascript function:

    document.getElementById("img1").src = 'data:image/jpeg;base64, ' + btoa(result);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search