Pedro
Pedro

Reputation: 1450

How to display an image from a database using ajax

I'm working on a simple mobile app that uses a database to store content including images and I'm using ajax to request the information and display that information on the app. The problem that I'm having is that the image don't appears and I don't know why

This is the code that I'm using to store the information enter image description here

$image = $_FILES['articleImg']['tmp_name'];
$date = date('l') .' '. date('d') . ', ' . date('Y');

$query = "INSERT INTO newsapp (title, company, category, details,
image, created) VALUES (:title, :company, :category, :details, :image, :created)";
$query_params = array(":title" => $_POST['title'],
   ":company" => $_POST['company'],
   ":category" => $_POST['category'],
   ":details" => $_POST['details'],
   ":image" => file_get_contents($image),
   ":created" => $date);

I have this file to that return the values in the database including the image:

$query = "SELECT id, title, company, category, details, image, created FROM newsapp";
try {
  $stmt = $db->prepare($query);
  $stmt->execute();
} catch (PDOException $ex) {
  die ('Failed to run query: ' . $ex->getMessage());
}
$row = $stmt->fetchAll();
echo json_encode($row);

Ajax function;

var url = "getnews.php"; 
    $.ajax({
        type: "POST",
        url: url, 
        crossDomain: true,
        cache: false,
        success: function(data)
            $.each(JSON.parse(data), function(i, value)
            {
                console.log(value.title); // return value from database
                console.log(value.image); // Return null
});

I have tryied to display the image by doing this, but it didn't work; Then I checked the value of image on the console and it says null

if try to display the image directly on php works fine.

echo '<img alt="blog"  src="data:image/jpg;base64,'.base64_encode( $rows['image'] ).'"/>';

Upvotes: 1

Views: 2485

Answers (1)

jtheman
jtheman

Reputation: 7491

You could base64_encode() the image before storing it in the DB, for it being possible to json_encode() when retrieved from the BLOB field. (as Lawrence said above, json_encode doesn't handle binary data)

IE: change the insert data

":image" => file_get_contents($image), 

to

":image" => base64_encode(file_get_contents($image)), 

Upvotes: 2

Related Questions