Search code examples
phpjqueryajaxdynamic-image-generation

Getting gibberish while returning image from php


I am using this code to generate barcode and i want to display it using ajax

<?php

require('class/BCGColor.php');
require('class/BCGDrawing.php');
require('class/BCGean8.barcode.php');

$font = new BCGFontFile('font/Arial.ttf', 18);
$color_black = new BCGColor(0, 0, 0);
$color_white = new BCGColor(255, 255, 255);

// Barcode Part
$code = new BCGean8();
$code->setScale(2);
$code->setThickness(30);
$code->setForegroundColor($color_black);
$code->setBackgroundColor($color_white);
$code->setFont($font);
$code->parse($_GET['code']);

// Drawing Part
$drawing = new BCGDrawing( '' , $color_white);
$drawing->setBarcode($code);
$drawing->draw();

header('Content-Type: image/png');

$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);

?>

and this is my html and js

<img src="" id="my_image" />
<a href="gen_barcode.php?code=1234567">Click</a>
$('a').on('click', function (e){
    $.ajax({
        url: "gen_barcode.php",
        type: 'GET',
        data: { code: '1234567' },
        success: function (data, textStatus, jqXHR) {
            console.log(data)
            $('#my_image').attr('src', data);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(data)
        },
    })
    e.preventDefault();
})

I am getting some gibberish odd looking string from server. How can i correct it. What am i doing wrong.


Solution

  • You're setting the src of the image to the actual data of the image. The src should be set to the URL of the image, rather than its content. Instead, set it to the url of the page generating the data:

    $('a').on('click', function (e){
        $('#my_image').attr('src', 'gen_barcode.php?code=1234567');
        e.preventDefault();
    });