Question

I am creating an image for captcha and I am having trouble in getting that image in ajax response.. Help is needed .. My code :

ajax part

$.ajax({
    type : "GET",
    url : "captcha.php",
    data : get_captcha_data,
    cache : false,
    success : function(r){
        $("#captcha").html('<img src="' + r + '" />');
    }


    });

php part

session_start();
$code=rand(1000,9999);
$_SESSION["code"]=$code;
$im = imagecreatetruecolor(50, 24);
$bg = imagecolorallocate($im, 22, 86, 165);
$fg = imagecolorallocate($im, 255, 255, 255);
imagefill($im, 0, 0, $bg);
imagestring($im, 5, 5, 5,  $code, $fg);
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: image/png');
print imagepng($im);

imagedestroy($im);

What seems to be the problem here?

Was it helpful?

Solution

As written in the comment above, you simply could implement the image with captcha.png as source:

$("#captcha").html('<img src="captcha.png">');

no AJAX request would be required, but to fulfill your request:

Your PHP part could be something like:

// Enable output buffering
ob_start();
imagepng($png);
// Capture the output
$imagedata = ob_get_contents();
// Clear the output buffer
ob_end_clean();

echo base64_encode($imagedata);

And the AJAX part could look like

success : function(r){
    $("#captcha").html('<img src="data:image/png;base64, '+ r +' ">');
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top