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����|�~,�ѿ
��7c��|S�����W�:�g��� ����K�z��A��D .͓�<�n��F� d�Qƹ̸{%�*֣�2�q7c�9UJ�0s��w�ߞ>ҥX��UaQG��w�bq8��
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'];.
In your php handler, write your image in a file;
$imgFolderPAth = "/path/to/img/";
imagejpeg($jpg_image,$imgFolderPAth . "image.jpg",100);
echo $imgFolderPAth . "image.jpg";
and in your js;
$.ajax({
type: 'post',
url: 'check-google-page-rank.php',
data: $('form').serialize(),
success: function (data) {
$('#my_pass').html('<img src="' + data + '"/>');
}
});
Or alternatively you can use;
imagejpeg($jpg_image,NULL,100);
$rawImageBytes = ob_get_clean();
echo "<img src='data:image/jpeg;base64," . base64_encode( $rawImageBytes ) . "' />";
and in your js, you can use as it is
Related
This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 5 months ago.
so, this is really hard to phrase, but I'm trying to use jQuery to move the file of an input element to a php file to put it into a message.
here's the code
HTML:
<form name="message" action="">
<input name="usermsg" type="text" id="usermsg"/>
<input name="userimg" type="file" id="userimg" accept="image/*"/>
<input name="submitmsg" type="submit" id="submitmsg" value="Send"/>
</form>
jQuery:
$(document).ready(function () {
$("#submitmsg").click(function () {
var clientmsg = $("#usermsg").val();
var clientimg = $("#userimg").val();
$.post("post.php", { text: clientmsg, img: clientimg });
$("#usermsg").val("");
return false;
});
//other stuff here
});
PHP:
$text = $_POST['text'];
$img = $_POST['img'];
$text_message = "<div class='msgln'><span class='chat-time'>".date("m-d, g:i A")."</span> <b class='user-name'>".$_SESSION['name']."</b> ".stripslashes(htmlspecialchars(preg_replace('/\pM/u', '', $text)))."<br><br>".$img."</div><!--". $_SESSION['ipAddr'] ."-->
";
file_put_contents('log.html', $text_message, FILE_APPEND | LOCK_EX);
If I add no file, it posts the message as usual (username and text), but if I add a file it says C:\fakepath\[file name and extension] note: fakepath is not a filler -- that's actually what it returns.
Please replace your js code and check again.
$(document).ready(function () {
$("#submitmsg").click(function (e) {
e.preventDefault();
var myFormData = new FormData();
myFormData.append('text',$('#usermsg').val());
myFormData.append('img',$('#userimg').get(0).files[0]); // Here's the important bit
$.ajax({
url: 'post.php',
type: 'POST',
data: myFormData,
dataType: 'json',
mimeType: 'multipart/form-data', // this too
contentType: false,
cache: false,
processData: false,
success: function(data){
$("#usermsg").val("");
return false;
},
error: function(error){
console.log(error);
}
});
});
});
php code:
$text = isset($_POST['text']) ? $_POST['text'] : '';
$img = $_FILES['img']['name'];
$target_file = basename($_FILES["img"]["name"]);
$name = isset($_SESSION['name']) ? $_SESSION['name'] : '';
// upload image in your root folder
if(move_uploaded_file($_FILES["img"]["tmp_name"], $target_file)) {
}
$text_message = "<div class='msgln'><span class='chat-time'>".date("m-d, g:i A")."</span> <p><b class='user-name'>".$name."</b></p> ".stripslashes(htmlspecialchars(preg_replace('/\pM/u', '', $text)))."<br><br><img src='".$img."' alt=''></div>";
// if you want to previous file delete.
if(file_exists('log.html')){
unlink('log.html');
}
file_put_contents('log.html', $text_message, FILE_APPEND | LOCK_EX);
echo $img;
I'm trying and failing to send the viewport width and heigth to a PHP file!
I know this or rather many similar questions about passing to PHP have already been asked and I've been going through these as well. However, I haven't figured out why it doesn't work for me...
I get the following output, where the second line would match the first, if the data had been passed:
Your viewport width is 1519x766
Width is: 880 and Height is 495
I just can't get the information passed to the PHP part - tried it like this in one file and also in two files, where I then call the php file using:
<?php include 'panzoom.php';?>
I use this code in the head:
<script>
var viewportwidth;
var viewportheight;
viewportwidth = window.innerWidth,
viewportheight = window.innerHeight
document.write('<p>Your viewport width is '+viewportwidth+'x'+viewportheight+'</p>');
$(document).ready(function() {
$.ajax({
url: 'http://localhost/index.php',
type: 'POST',
dataType: 'json',
data: {
width : viewportwidth,
height : viewportheight
}
});
});
</script>
<?php
$GLOBALS['directory'] = "photos/frontpage/";
if(isset($_POST['width']) && isset($_POST['height'])) {
$GLOBALS['width'] = $_POST['width'];
$GLOBALS['height'] = $_POST['height'];
}else{
$GLOBALS['width'] = 880;
$GLOBALS['height'] = 495;
}
$width = $GLOBALS['width'];
$height = $GLOBALS['height'];
echo '<p>Width is: ' . $width . ' and Height is ' . $height . '</p>';
?>
You have posted a JSON string to the PHP script and it is called data so you should be looking for $_POST['data']
Also as it is posted as a json string, in order to make sense of it in PHP you normally decode it to either an array or a string using json_decode()
You also dont need to create all the variables in javascript to clutter up the global namespace.
So try this
<script type="text/javascript">
document.write('<p>Your viewport width is '+
window.innerWidth+'x'+window.innerHeight+'</p>');
$(document).ready(function() {
$.ajax({
url: 'index.php',
type: 'POST',
dataType: 'json',
data: {
width : window.innerWidth,
height : window.innerHeight
}
});
});
</script>
<?php
$GLOBALS['directory'] = "photos/frontpage/";
if( isset($_POST['data']) ) {
$obj = json_decode($_POST['data']);
$GLOBALS['width'] = $obj->width;
$GLOBALS['height'] = $obj->height;
}else{
$GLOBALS['width'] = 880;
$GLOBALS['height'] = 495;
}
$width = $GLOBALS['width'];
$height = $GLOBALS['height'];
echo '<p>Width is: ' . $width . ' and Height is ' . $height . '</p>';
?>
I have a following HTML and Javascript code:
<script type="text/javascript">
$(function() {
$('#form_1 input').on('change', function() {
val = $('input:radio[name=graf]:checked').val();
$.ajax({
type: 'POST',
data: ({graf_id: val}),
url: 'rrd_image.php',
success: function(data) {
$('#div_1 img').attr('src', data);
}
});
});
});
</script>
<div id="div_1">
<form id="form_1">
<input type="radio" name="graf" value="1">Daily
<input type="radio" name="graf" value="2">Weekly
<input type="radio" name="graf" value="3">Monthly
</form>
<img src="default.png">
</div>
And the rrd_image.php:
$graf_id = $_REQUEST['graf_id'];
$tmpfile = "/tmp/rrd.png";
// rrd_graph options...
rrd_graph($tmpfile, $options);
header( "Content-Type: image/png" );
header( "Content-Length: " . filesize( $tmpfile ) );
$fp = fopen( $tmpfile, 'rb' );
if( $fp ) { fpassthru( $fp ); }
fclose( $fp );
exit();
The rrd_graph.php itself is working, but when i click one radio-button, the HTML page
do not reload the right PHP generated rrd image.
The problem is your PHP file is returning an image, not a URL. What I would do is pass your graf value, along with a time string, in the query string and then tell JS to load that image instead
$(function() {
$('#form_1 input').on('change', function() {
var val = $('input:radio[name=graf]:checked').val();
var time = new Date().getTime();
$('#div_1 img').attr('src', 'rrd_image.php?graf_id=' + val + '&time=' + time);
});
});
You don't need AJAX anymore because the time parameter will always be different and thus your browser won't cache it.
I'm rendering a screenshot with html2canvas 0.4.0 and want to save it as image on my webserver.
To do so, I've written the following function:
JavaScript
function screenShot(id) {
html2canvas(id, {
proxy: "https://html2canvas.appspot.com/query",
onrendered: function(canvas) {
$('body').append(canvas); // This works perfect...
var img = canvas.toDataURL("image/png");
var output = img.replace(/^data:image\/(png|jpg);base64,/, "");
var Parameters = "image=" + output + "&filedir=" + cur_path;
$.ajax({
type: "POST",
url: "inc/saveJPG.php",
data: Parameters,
success : function(data)
{
console.log(data);
}
}).done(function() {
});
}
});
}
saveJPG.php
<?php
$image = $_POST['image'];
$filedir = $_POST['filedir'];
$name = time();
$decoded = base64_decode($image);
file_put_contents($filedir . "/" . $name . ".png", $decoded, LOCK_EX);
echo $name;
?>
After the canvas is rendered I can perfectly append it to the HTML body, but saving it on my server result in a corrupted (?) file.
I can read the dimensions in IrvanView, but the image is transparent / empty?
The file is about 2.076 KB large. So it's not really empty.
I tried this with JPEG as well and it results in a corrupted file and IrfanView says something like "bogus marker length".
The screenshot has the dimensions of 650x9633. Is it to much data for a POST-Method?
In case someone stumbles over the same problem, here is how I solved it:
The problem depended on the fact, that + in URLs is interpreted as an encoded space (like %20) by most servers. So I needed to encode the data first and then send it via POST to my designated PHP function.
Here is my code:
JavaScript
function screenShot(id) {
html2canvas(id, {
proxy: "https://html2canvas.appspot.com/query",
onrendered: function(canvas) {
var img = canvas.toDataURL("image/png");
var output = encodeURIComponent(img);
var Parameters = "image=" + output + "&filedir=" + cur_path;
$.ajax({
type: "POST",
url: "inc/savePNG.php",
data: Parameters,
success : function(data)
{
console.log("screenshot done");
}
}).done(function() {
//$('body').html(data);
});
}
});
}
savePNG.php
<?php
$image = $_POST['image'];
$filedir = $_POST['filedir'];
$name = time();
$image = str_replace('data:image/png;base64,', '', $image);
$decoded = base64_decode($image);
file_put_contents($filedir . "/" . $name . ".png", $decoded, LOCK_EX);
echo $image;
?>
Cheers!
so I have a Ajax-Scripts thats permanently reloads a PHP-Page:
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
loadstatus();
});
function loadstatus(){
$.ajax("innopbx.monitor.php").done(function(data){
document.getElementById("status").innerHTML = data;
setTimeout('loadstatus()', 1000);
});
}
</script>
And the PHP-Page being reloaded shows HTML-Canvas like this:
echo '<canvas id="' . $ui->guid . '" width="100" height="100" class="clear" style="border:1px dotted"></canvas> ';
echo '<script type="text/javascript">
var a_canvas = document.getElementById("' . $ui->guid . '");
var a_context = a_canvas.getContext("2d");
var gradient = a_context.createLinearGradient(0, 0, 0, 100);
gradient.addColorStop(0, "#bbffbb");
gradient.addColorStop(1, "#55ff55");
a_context.fillStyle = gradient;
a_context.fillRect(2, 2, 96, 96);
a_context.font = "10px sans-serif";
a_context.fillStyle = "black";
a_context.fillText("' . $ui->cn . '", 5, 20);
</script>';
When I navigate to the PHP-Page directly the Canvas is drawn exactly as expected. But when I navigate to the Page with the AJAX-Function that reloads the PHP-Page permanently I only see the dotted border. Its not filled and no Text is there.
Do you have any idea? Thanks in advance!
You can try to add document.getElementById("status") as target parameter of $.ajax.
var t = document.getElementById("status");
function loadStatus(){
$.ajax({url: "innopbx.monitor.php", target: t, success: function(){
setTimeout(loadstatus, 1000);
});
}
It should deal with the js execution, rather than innerHTML = ....