0

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.

Cody
  • 2,480
  • 5
  • 31
  • 62

1 Answers1

2

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();
});
James Thorpe
  • 31,411
  • 5
  • 72
  • 93
  • Ok thanks it works, now how can i implement when someone clicks download the image – Cody Jan 14 '15 at 10:35
  • 1
    @Cody If you have another question, feel free to ask another one - comments aren't the place to do so. Though it sounds like [this question](http://stackoverflow.com/questions/17527713/force-browser-to-download-image-files-on-click)'s answers may answer it (ie use the `download` attribute). – James Thorpe Jan 14 '15 at 10:37
  • thanks for response i am getting the image now, but tell me how download it when i click it. Most of the code is same that's why not asking another question. Thanks – Cody Jan 14 '15 at 10:41