Search code examples
javascriptphpmysqlajax

Blob image displaying from database


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)
                                                    
                                }}
                            })

Solution

  • 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.