Showing image binary data using javascript

I am trying to get the image stored in db as json and diplay the image using javascipt. but not able to view the image. i tried fire bug to view the html code img src is showing null.

here is my php code to get the data from db table:

<?php
header('Content-type: application/json');

include 'connect.php';

$b_id=$_GET['b_id'];
$c_id=$_GET['c_id'];

$sql_select=mysql_query("SELECT * FROM business_directory WHERE business_category_id=$b_id") or die(mysql_error());

$records = array();

if(mysql_num_rows($sql_select)>0){

while($row=mysql_fetch_array($sql_select)){
    $records[] = $row;  
}
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
}else{

    echo 'data not selected';
}
?>

Here is javascript code:

function get_business(){

$.ajax({
        url:'http://localhost/ajax_practice/php/get_business.php',
        dataType: 'jsonp',
        jsonp: 'jsoncallback',
        timeout: 5000,

        success:function(data){
            $.each(data, function(i,item){
                var output="";
                    $(".gallery").append(output);

                        output+="<li>";

                        output+="<a href='category.html?b_id="+item.id+"' data-transition='slide' rel='external'>";
                        output+="<img src='"+item.business_icon+"'/>";
                        output+="<span>"+item.business_name+"</span";
                        output+="</a>";
                        output+="</li>";
                    $(".gallery").append(output);


            });
        }
    });

}

Can onyone help me that how can i get the data from database and show it using javascript.

Upvotes: 0

Views: 2124

Answers (4)

Enamul Haque
Enamul Haque

Reputation: 5053

You can use

output +="<img style='width: 30px; width:50px;' src='data:image/png;base64,"+item.business_icon+"' />";

Upvotes: 0

SaminatorM
SaminatorM

Reputation: 630

You can't send it in binary format with json, so you can encode it as base64 string and send it as string. In client side you can use

<img src="data:image/jpg;base64,base64Data" />

base64Data - base64 string coming from the server

You can see more info,

Showing image data using javascript

Upvotes: 1

user568109
user568109

Reputation: 47993

I am not sure what is the format of image stored in database. You say it is stored as json.

If it is base64 already, try this

output+="<img src='data:image/png;base64,"+item.business_icon+"'/>";

or if it is binary(raw image), try this

output+="<img src='data:image/png;base64,"+atob(item.business_icon)+"'/>";

To know what format it is just output item.business_icon on console if has strange characters, then it is binary form.

Upvotes: 0

jcubic
jcubic

Reputation: 66478

You need to encode your image as base64 and use data url data:image/png;base64,<DATA>

https://en.wikipedia.org/wiki/Data_URI_scheme

Upvotes: 0

Related Questions