Guide on presenting an image retrieved from a database with ajax

I am currently developing a straightforward mobile application that utilizes a database to store various types of content, including images. I have implemented ajax requests to retrieve this information and display it within the app. However, I am encountering an issue where the images are not appearing as expected, and I am unsure of the reason behind this.

Below is a snippet of the code used to save the information:

https://i.stack.imgur.com/unjcQ.jpg
$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);

The following script is responsible for retrieving values from the database, including the images:

$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);

Here is the Ajax function being utilized:

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 attempted to display the image using the given method, but encountered issues; upon inspecting the image value in the console, it returns null. Although, displaying the image directly via PHP functions correctly.

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

Answer №1

To ensure smooth storage and retrieval of images from the database, consider encoding the image using base64 before insertion and decoding it back using json_encode when fetched from the BLOB field. (as mentioned by Lawrence earlier, binary data is not handled well by json_encode)

For instance, modify the insert query like this:

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

to

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a COALESCE statement in CakePHP 3 query builder

Is there a way to incorporate the COALESCE() statement directly in the query builder? SQL SELECT COALESCE(n.value, p.value) AS value FROM nodes n LEFT JOIN parents p ON p.id = n.parent_id PHP I am currently retrieving both child and parent values separ ...

experiencing a discrepancy when transferring a variable from a model to a controller in PHP as it returns

Encountering a null value issue when passing a variable from the model to the controller in PHP using the code below. The problem lies in not being able to successfully pass the quantity from the model to the controller. Model: public function getcomboPr ...

What is the best way to choose the contents of every JSON array?

Struggling to extract the necessary values from JSON data: foreach ($users as $row) { $usersDepartement = json_decode($row["departement"]); var_dump($usersDepartement); } Output obtained: array(1) { [0]=> object(stdClass)#5 (1) { ["u ...

Dividing CSV Data into Two File Outputs

I've got a CSV file that's structured like this: Docushare Host locale, created_at, version en,Wed Feb 21 17:25:36 UTC 2018,07.00.00.C1.609 User handle, client_data, docCountQuota User-12,,-2 Document handle,client_data,cfSpecialWords Document ...

Creating a simple form page using Express JS

I am a beginner in the world of Node Js and Express Js, currently diving into learning from a book titled "Jump Start NodeJs" by Sitepoint. The author has provided a simple Login Form page as an example in the book. However, when trying to implement the co ...

Angularjs - Repeatedly reloading identical images

Whenever I use ng-src in the <img> tag and change the ng-src by clicking next or previous buttons, the browser reloads the image even though it's already loaded. This results in a not-so-smooth experience as the image is downloaded again before ...

The embedded component is throwing an error stating that the EventEmitter is not defined in

Currently, I am delving into the realm of angular and facing an issue. The problem lies in emitting an event from a component nested within the main component. Despite my efforts, an error persists. Below is a snippet of my code: import { Component, OnIn ...

Issues with executing the intended task for a jQuery onclick function

I have a unique jQuery script set up where when #block4 is clicked, the .maincontent div will show. Initially it works perfectly by showing and then hiding the div. However, after the first two clicks, the .maincontent div shows and immediately disappears. ...

Error message occurs in jQuery form when optional fields are left empty, displaying a "missing ) after argument list" notification

I've encountered an issue with my form that submits to a jQuery plugin I developed. Until now, everything worked smoothly, but when I added optional fields to the form, things started going wrong. The input text fields in the form are initially popula ...

Using Django's template language to pass variables into an AJAX request's data

I am facing an issue with sending variables created in a view via ajax post request. When I inspect the chrome, it seems like nothing is being properly sent to my post request. Below is the javascript function causing the problem: function submitDataTabl ...

Transform spaces into %20 from an HTML input field by utilizing JavaScript or jQuery

Hi there, I'm encountering an issue with the input field on my website where users can enter search terms. I am currently extracting the user's input value and adding it to a URL string. jQuery("#searchButton").click(function(){ var simpl ...

My navigation menu has a nested ul, but on mobile devices, it doesn't display all the items in the list. What could be causing

When I click on "Products" in my main navigation, only the first 6 items are displayed from a nested ul. How can I make all of them display when the user clicks on "Products"? Is this a CSS issue or a problem with the script? Here's a screenshot for r ...

Receiving an error when triggering an onclick event for a checkbox in TypeScript

I am creating checkboxes within a table using TypeScript with the following code: generateTable(): void { var table = document.getElementById("table1") as HTMLTableElement; if (table.childElementCount == 2) { for (var x = 0; x < 2; x++) ...

How can I access a field value in a Scala class without using reflection and instead utilizing strings?

class Person { name: String, age: Int } val person = Person( name = "John", age = 30 ) Assuming we have the string "name", I need to retrieve the value of person.name, which is "John". Can this be achieved without relying on reflection, c ...

PNG file is not displayed on React TSX page despite absence of any errors

I've implemented this initial design template from GitHub (https://github.com/vikpe/react-webpack-typescript-starter). Additionally, I'm utilizing react-bootstrap and have a container that includes a backgroundImage. const heroImage = require(&q ...

The values returned by a NodeJS script in the Python shell are identical to those returned by Node

The following program was developed to address an issue in another application. In this program, a Python script is called from Node.js to perform a task. The Python script returns results that are then used in Node.js. NodeJS : var pythonShell = require ...

Is Javascript necessary for submitting a form to a PHP script?

In my current project, I am working on a page to edit information in a database. While I know how to create the form in HTML and the PHP script that runs on the server, I am facing a challenge with JavaScript. My understanding of JavaScript is limited, and ...

Updating Navigation Bar Font

I am a novice in the process of constructing my own navigation bar for my website, and I am encountering difficulties when trying to customize the font (color, font-family, etc). Currently, the links in my navigation bar (such as home, contact, store, etc ...

Leveraging PHP to extract terms that begin with the "@" symbol within a string

As a user posts a comment, I aim to extract all the words that begin with an @ symbol. For example: string 'Check this out @user1. It's a photo of @user2 and @user3.' On the PHP side, my goal is to capture user1, user2, user3 in order to n ...

Converting the content of a div into an image using PHP

Does anyone know a method in PHP to convert the HTML div content into a JPG or PNG image? <div class="canvas-object" style="background-color: rgb(247, 213, 183);"> <img id="img1" class="img" src="logo.png" style="width:110px; heigh ...