user1613360 user1613360 - 7 months ago 34
Javascript Question

imagejpeg() php return junk values

My jQuery Ajax code is:

<div class="page_rank">
<form name="searchForm" id="searchForm" method="post">
<span class="my_up_text">ENTER THE WEBSITE TO CHECK GOOGLE PAGE RANK:</span>
<br /><br />
<input type="text" name="my_site"/></div><div class="p_ity"><input type="submit" class="btn" value="PAGE RANK" /> </form></div><div id="my_pass"></div>

<script>
function sub_form()
{
document.forms["searchForm"].submit();
}

$(function () {
$('form#searchForm').on('submit', function(e) {
$( ".p_ity" ).hide();

$.ajax({
type: 'post',
url: 'check-google-page-rank.php',
data: $('form').serialize(),
success: function (data) {
$('#my_pass').html(data);

}
});
e.preventDefault();
});
});
</script>


My php code is:

<?php
header('Content-type: image/jpeg');
require('./get_page_rank.php');
$url=$_POST['my_site'];
//echo $url;
$pr = new PR();
//$rank= $pr->get_google_pagerank($url);
$rank=$pr->get_google_pagerank($url);

// Create Image From Existing File
$jpg_image = imagecreatefromjpeg('./images/page-rank/G.jpg');
if($jpg_image)
{
// Allocate A Color For The Text
$white = imagecolorallocate($jpg_image, 0, 0, 0);

// Set Path to Font File
$font_path = './images/page-rank/Helvetica.TTF';

// Set Text to Be Printed On Image
$text = $rank;

// Print Text On Image
imagettftext($jpg_image, 85, 0, 305, 100, $white, $font_path, $text);

// Send Image to Browser
imagejpeg($jpg_image,NULL,100);

// Clear Memory
imagedestroy($jpg_image);
}
?>


It works perfectly if I execute the PHP separately with manual input so I think the problem is with jQuery
html()
function. I am sure the image is not corrupted and I am using utf-8 encoding and I also tried
base64_encode(imagejpeg())
but got the same output.

OUTPUT:

��*����D\�@��梸�����[[h� ��0 s��('�y\�ӎ+��_�P 7��){�i�i��ĽOH�
_��:�� VV���y�x���o~�Eh��R��U�1�C����|�~,�ѿ
��7׼c��|S�����W�:�g��� ����K�z��A��D .͓�<�n��F� d�Qƹ̸{%�*֣�2�q7c�9UJ�0s��w�ߞ>ҥX��UaQG��w�bq8��

Answer

imagejpeg() outputs the image to browser directly, so the response is not the html content you could use with .html(), you don't have to use ajax in this case, the url should be used as the src of an image tag.

You could do like below:

$(function () {
    $('form#searchForm').on('submit', function(e) {
        $( ".p_ity" ).hide();
        $('<img />').attr('src', 'check-google-page-rank.php?my_site='+ encodeURIComponent($('[name= "my_site"]').val())).load(function() {
          $(this).appendTo('#my_pass');
        });
        e.preventDefault();
    });
});   

And change $url=$_POST['my_site']; to $url=$_GET['my_site'];.