Displaying generated image via ajax - javascript

I have form where i can write text. I want this text to be generated on image. I have it and it works, i'm using imagepng($im). The problem is that i need to print that image, and have a "print" button. Because of header('Content-Type: image/png') i cant use html on page where i generate it so i would like to use ajax. This is my actual code which well is little mixed, i tried something with base64 but never used it and i failed. Acutally my code isnt even showing errors(shows with datatype json). I dont really know how to do it. Didn't found it anywhere. Please help i don't know what to do ;_;
Code:
<script type="text/javascript">
jQuery(function($) {
$(document).ready(function()
{
$( "#form_formularz" ).submit(function(e)
{
var data=JSON.stringify($('form').serialize())
e.preventDefault();
$.ajax({
type: 'post',
url: 'http://example.com/transfer_generator.php',
data: data,
error: function(a,b){console.log(a);console.log(b)},
success: function(cbdata){
console.log(data);
console.log(cbdata);
$('#form_image').html('<img src="data:image/png;base64,' + cbdata + '" />');
}
});
});
});
});
</script>
<div id="form_image">
</div>
EDIT:
changed "succes" to "success" and added cbdata in success: function(){
There is '
// Set the content-type
header('Content-Type: image/png');
// Create the image
$im = ImageCreateFromPNG( "image.png" );
/* adding some text, everything okay */
imagepng($im);
I tried to add echo 'base64_encode(imagepng($im));' but didnt work for this.

You have two errors in your code. Fix those before debugging further.
The success method is misspelled.
The success method has no cbdata argument. Where are you declaring this?
Try the following:
...
success: function(cbdata){
console.log(data);
console.log(cbdata);
$('#form_image').html('<img src="data:image/png;base64,' + cbdata + '" />');
}
...
EDIT: In response to your edit, do the following in your PHP file:
Remove the header statement.
You need to send back the string contents of the base64 encoded image. Something like this:
$fileName = 'my-temp-image.png';
imagepng($im, $fileName);
imagedestroy($im);
$base64Image = base64_encode(file_get_contents($fileName));
unlink($fileName);
echo $base64Image;

Related

loading message with jquery and calling id

I made a small shoutbox for my site and I am loading the page with jquery and storing all my data in a database like usual. anyways, when a user wants to edit a post they double click on it and they can edit their post. I am using the following code to show the editor and let them do whatever they need to with it. sadly something isn't working and that something is:
i cant include my tag id in the url: on my ajax call
Here's is a look at the code
<? php
public function make_editable($shout, $id) {
$string = "<span ondblclick=\"javascript: edit_shout('".$id."'); return false;\">".$shout."</span>";
return $string;
}
?>
<script type="text/javascript">
function edit_shout($id) {
$("#panel_edit_shout").slideDown();
$('#update').val($id);
$('#delete').val($id);
$.ajax({
url : "/chat?loadModule=3&id={$id}",
dataType: "text",
success : function (data) {
$("#updateshoutmessage").val(data);
}
});
}
</script>
If i replace the {$id} with say, 1 for example, then it works correctly and loads the text of shout id 1 into the field like its supposed to, but if I try and load dynamically using $id, it just gets an error because the $id is coming up as blank... Thanks for your help :).
Uhm... if the variable is in javascript you can do:
url : "/chat?loadModule=3&id=" + $id,
If it is php then you have to do
url : "/chat?loadModule=3&id=<?=$id?>",
But like the other guys said, without more code we can't help much.
Very easy fix thanks to #Dranes for his help. Simply needed to add +
<script type="text/javascript">
function edit_shout($id) {
$("#panel_edit_shout").slideDown();
$('#update').val($id);
$('#delete').val($id);
$.ajax({
url : "/chat?loadModule=3&id=" + $id,
dataType: "text",
success : function (data) {
$("#updateshoutmessage").val(data);
}
});
}
</script>

Getting a PNG image from PHP using AJAX

I have a PHP script that computes the next value in a time series data and plots that to a graph as a PNG image. I will provide this data through AJAX, and PHP creates the PNG image. Now, how do I get the generated PNG image from PHP as an AJAX response? The code is as follows:
PHP:
<?php
$data = json_decode($_POST['data']);
// Some code to calculate the next value in this series
plotRenderRegression( $polynomialRegression, $coefficients, 0, 11 , $colorMap[ "Blue" ] );
header( "Content-Type: image/png" );
echo imagePNG( $image );
?>
JS:
$.post({
dataType: "image/png",
url: "predict.php",
data: {
sent: true,
data: "[[1,0.63151965],[2,0.58534249],[3,0.43877649],[4,0.2497794],[5,0.07730788],[6,0.08980716],[7,0.11196788],[8,0.19979455],[9,0.4833865],[10,0.9923332]]"
},
success: function (img) {
console.log(img)
i = new Image();
i.src = img;
console.log(img);
$("#imgdiv").prepend(i);
},
error: function (error, txtStatus) {
console.log(txtStatus);
console.log('error');
}
});
Console Output:
�PNG
IHDRX�Ao�NPLTE������00�������000������������333MMMfff���������������vD���IDATx��][��*�*>���o���$ ?$[��ɑq� Ι�����������2������Fp�;D33������c���وeĪF�iO̮H�����r*3'���[N
o~p#���X��ˀ���ub��T�X�,���׽���q�.�R��}� �]��#æy����l}�
}:U���,�����'�w�W_�0S9ԡ�wl�0�עOfTc8qw��9,=�s����7��^��h�U�1b-��?��鎿G����Ag��}����7Gg��GY���R��4y� LE����8'o� �+L>A��ʻ�e�hry��سد�끷�j����`#�����)ժϜΟc-)_ck��� ���=2�W�rY�X�gY]���1�H�T�3�*�]'�V�T̼t$���ྑN��&�K���%qp�cuf���2}8����`�PA'VF%6�PoC-6!���ky����8䪏U�:������,�Ƌ�
�9Uby���W�
���共� .....
What am I doing wrong here ?
UPDATE 1:
I've changed the JS code as follows, but it still get a broken image
success: function (data) {
$('#imgdiv').html('<img src="data:image/png;base64, ' + btoa(unescape(encodeURIComponent(data))) + '" />');
}
You can't set SRC to the image itself. You can solve the problem in two ways:
1- Create a temporary file and return a link to it in your PHP file
2- base64 encode the PNG and pass it to src the way you're currently doing.
On both those ways, you'd probably have to lose the "dataType" filter of jQuery for the response to be interpreted as successful.
Example of final HTML (src set via your JavaScript Ajax):
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNby
// blAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC />"
<img src="data:image/png;base64,[base64_encoded_png_goes_here] />"

Using Ajax, JavaScript and HTML to post some data

Hello I´m very frustated because I can´t connect to my database to retrieve some files.
I have my normal html code (index.html) which adds a javascript:
<script src="js/connection.js"></script>
The javascript (connection.js) looks something like this, which detects from a grid of elements the selected element and gets it´s text:
var texto="";
function getData($dia){
//Variable $dia is set up correctly, no problem
var dia=$dia;
/* Send the data using post*/
$.ajax({
url: "php/setup.php",
type: "post",
data: {'fecha':dia},
contentType: "application/json",
datatype: "json",
success: function(){
alert("Exito");
},
error:function(){
alert("failure");
}
});
}
//Get the desired text upon click on the grid item
$(document).ready(function(){
$(".grid__item").click(function(){
$texto=$(this).html().substring(($(this).html().indexOf(">"),($(this).html().indexOf(">")+1)),$(this).html().indexOf("</h2>"));
getData($texto);
});
});
Finally using Ajax I pass the variable 'fecha', the problem is that I think it´s not making a proper connection with my php file since nothing is printing (I have a method which prints to console)
I set the post method like this (PHP file starts here):
debug_to_console("Print Something");
$fecha = mysql_real_escape_string($_POST['fecha']);
getPageData($fecha);
Which calls this method:
function getPageData($dia){
$sql = ("SELECT * FROM Comentarios WHERE dia='$dia'");
$result = mysqli_query(connectToDb(),$sql);
$num_rows = mysqli_num_rows($result);
$html="";
$boolean=true;
if($num_rows>0) {
while($row = $result->fetch_assoc()) {
if($boolean==true){
$html.='<div class="gray"><div class="comentario">'.$row["comment"].'</div><div class="timestamp">'.$row["dia"].'</div></div>';
$boolean=false;
}else{
$html.='<div class="white"><div class="comentario">'.$row["comment"].'</div><div class="timestamp">'.$row["dia"].'</div></div>';
$boolean=true;
}
}
echo json_encode(array('html'=>($html.'<br>'.'<div class="fondo_gen"> div></div></div>'),'texto'=>$dia));
} else {
echo json_encode(array('html'=>'<div class="transparent"><div class="nada">No hay comentarios aun :(</div></div>','texto'=>$dia));
}
}
PHP file ends here
I know that it's connecting to the database since a made a "dummy.php" file which connects to the same database and table and adds a record, without problem. I´m not really sure which is the problem, I could really appreciate it if you could help me.
PS:
My folders are setup like this:
index.html
js (folder)
a. connection.js
php (folder)
a. setup.php
.
Thanks and sorry for my crappy english
Never mind, I got it fixed, I replaced the Ajax part with:
$.post("php/setup.php",
{
fecha: dia
},
function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
and received the variable using
if (isset($_POST["fecha"])){
$fecha = $_POST["fecha"];
getPageData($fecha);
}else{
echo "Got nothing";
}
Thanks anyway, I appreciate the help

jQuery and Ajax Loading Images

I have a site with a giant portfolio with a ton of high-res images.
I do not want to resize these images, but I would like to be able to pull them in async.
Come forth jQuery .ajax
But my code is wrong, somehow. What it does is seem to pull in the page, instead of the image "src"
Can you help:
// Load in the images via ajax:
var $imgs = $('.ajax-image');
$imgs.each(function(i){
var $imgsrc = $(this).attr('src');
var $url = '/php/pull-image.php?i=' + $imgsrc;
$.ajax({
url : $url,
mimeType: "text/plain",
processData : false,
cache: false,
success: function (html) {
$(this).attr('src', html);
}
});
});
and the PHP:
$path = $_GET['i'];
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
echo 'data:image/' . $type . ';base64,' . base64_encode($data);
Image tags are simply: <img src="http://example.com/images/image.ext" />
What am I doing wrong here? and how can I fix it?
As I mentioned in my comment, I don't see how this would do what you want but to address your current problem: It is probably caused because of this in the context of the success function, is not the same as the this in the context of your each() function.
You should save the element so that you can access it in the success function:
$imgs.each(function(i){
var el = $(this),
$imgsrc = el.attr('src'),
$url = '/php/pull-image.php?i=' + $imgsrc;
$.ajax({
url : $url,
mimeType: "text/plain",
processData : false,
cache: false,
success: function (html) {
el.attr('src', html);
}
});
});
Edit: There is no real need to use ajax / php here to set the source of the image. You could also generate some images in javascript (in batches), add an onload() function for the images and set the source of your html elements when they are loaded and then get the next batch. See for example this question: JavaScript: Load an image from javascript then wait for the "load" event of that image
Your php page is getting an error because you are not passing in anything for parameter i. Your php is therefore throwing a 404 error - a full HTML response.
I think you have a javascript syntax error that is causing this:
url : '/php/pull-image.php?i=' . $imgsrc,
Replace this line with:
url : '/php/pull-image.php?i=' + '<?php echo json_encode($imgsrc); ?>' ,

Ajax POST is not posting onclick to current page

Alright so this has been bugging me for a long time now... I have tried everything but I cant get it to work!
So what I want to have is a link that acts as a button, and once you click it, it POSTs an ID number of the button in the form "{ 'id' : id }"
edit-homepage.php:
<script>
$(function() { // document ready
$('a.inactive').on('click', function(event) {
event.preventDefault(); // instad of return false
var id = $(this).data('id');
// use $.post shorthand instead of $.ajax
$.post('edit-homepage.php', {id: id}, function(response) {
// after you get response from server
editSlide(id);
});
});
});
</script>
The a href button is created using PHP and I want it to call the ajax function postID( id ) which will post the id so that later I can populate a form via PHP using the posted id.
edit-homepage.php:
echo '<li><a class="inactive" id="slide-'.$info["id"].
'" onClick="postID('.$info["id"].'); editSlide('.$info["id"].'); return false;">'
.'<img src="../images/'.$info["img"].'" width="175"/><p>Edit Slide '
. $info["id"] .'</p></a></li>';
Currently, when I click the link, it opens the alert but it is EMPTY or Undefined. It is supposed to display "ID: 1" for example if the link clicked has a ID of 1.
edit-homepage.php:
<script>
function editSlide($id) {
<?PHP
if (isset ($_POST['id'])) {
echo "alert('success!2');";
}$id = !empty($_POST['id']) ? $_POST['id'] : '';
$data = mysql_query("SELECT * FROM slider WHERE id='$id'") or die(mysql_error());
$info = mysql_fetch_array( $data );?>
document.getElementById("edit-slide-id").innerHTML="Edit Slide #"+$id;
document.getElementById("edit-form").style.display = "block";
document.getElementById("short-title").value="<?PHP echo $info['s_title']; ?>";
}
</script>
Thanks!
With jquery, you don't need to use attributes to attach events, like that:
$(function() { // document ready
$('a.inactive').on('click', function(event) {
event.preventDefault(); // instad of return false
var id = $(this).data('id');
// use $.post shorthand instead of $.ajax
$.post('edit-homepage.php', {id: id}, function(response) {
alert('ID:' + response);
// after you get response from server
editSlide(id);
});
});
});
As of server side, try replacing raw
<?PHP echo $_POST['id']; ?>
With
<?php echo !empty($_POST['id']) ? $_POST['id'] : '' ?>
You likely get notice about Undefined index id, which breaks javascript if there is no post data.
UPDATE
edit-homepage.php shold be separated something like that:
if(!empty($_POST)) {
// here you process your post data and return
// only wenever you want to pass to script
// not all the html
} else {
// here you output html and scripts, but don't do request processing
}
You should always remember, that your HTML rendering must always be separated from your logic. It is better to put views in separate files from logic, though it is not required, it is much easier to debug and maintain.
You can not include PHP code that is supposedly to run after the ajax call. The PHP code will be run only to generate the page. Anything you want to include in alert should be provided in the ajax response, in your case the data variable.
You need to use alert('ID: ' + id).
The $_POST['id'] part of the script does not react to the AJAX request. It is whatever the $_POST['id'] value is when the script is output to the browser (i.e. when the page is first loaded).
You will see this if you view the source.
alert ("ID:"+data);
then only you will get response
or
alert("ID"+id);
this will alert the id passes to function
http://jsfiddle.net/U54ME/
$(".checkthisclass").click(function() {
$.ajax({
type: "POST",
url: "edit-homepage.php",
data: { 'id' : $(this).attr("slideid"); },
success: function(data) {
alert(data);
}
});
}
});
--
<ul>
<li><a class="inactive checkthisclass" id="slide-5" slideid = "5" ><img src="http://blog.entelo.com/wp-content/uploads/2013/04/stackoverflow-logo.png" width="175"/><p>Edit Slide 5</p></a></li>
</ul>

Categories

Resources