Michael Yousef Michael Yousef - 8 months ago 49
Ajax Question

Send image from php server using ajax call

The short of what I'm trying to do is search for a file and display a picture from the server. The HTML has a simple search bar that allows you to type in a search term. The JavaScript uses an ajax request to call the PHP file, and the PHP finds the image on the server and sends it back to be displayed.

What happens right now is that the image isn't displayed, and I get an icon indicating some invalid image. The ajax call appears to be working, but I think the data I'm sending back isn't correct. I've been trying to search for it but everyone seems to have a different opinion on how to do it and it's kind of confusing.


<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
<script src="search.js"></script>
<style type="text/css"></style>
<h1>My Page</h1>
<input type=text name="search" id="searchbox" placeholder="Search...">
<input type=button value="Search" id=search><br>
<div id="images"></div>


$(document).ready(function() {
$("#search").on('click', function(){
url: '/search.php',
type: 'POST',
data: $("#searchbox").serialize(),
success: function(data) {
error: function() {


if(isset($_POST['search'])) {
$searchterm = $_POST['search'];
$image = "images/".$searchterm.".jpeg";
echo '<img src="data:image/jpeg;base64,'.base64_encode($image).'">';
else {
echo 'Error: image not found';

PS. For the moment, I'm ignoring any sort of error checking, I'm just trying to get it working and assuming the input is all valid



  1. Try this link:

Image Data URIs with PHP

if(isset($_POST['search'])) {
    $searchterm = $_POST['search'];
    $image = "images/".$searchterm."jpeg";
    $imageData = base64_encode(file_get_contents($image));
    $src = 'data: '.mime_content_type($image).';base64,'.$imageData;
    echo '<img src="', $src, '">';
  1. Debug the actual HTTP traffic between your jQuery/Browser and your PHP/back-end server. You can use a tool like Telerek Fiddler or Firebug, among many others.

'Hope that helps!