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); ?>' ,
Related
I worked on a method tonight that allowed me to make hidden div's and then use .text() with jQuery to get the contents of the hidden div, but now I am stuck with a similar scenario. You can see my original question here: How can you put PHP inside a Javascript?
Basically, I have a script to get Google+ followers, which works great:
<script>
var profileid = 'xxx';
var apikey = 'xxx';
var url = 'https://www.googleapis.com/plus/v1/people/' + profileid + '?key=' + apikey;
$.ajax({
type: "GET",
dataType: "json",
url: url,
success: function (data) {
var googlefollowcount = data.circledByCount;
$(".googleFollowerCount").html(googlefollowcount.toLocaleString('en'));
}
});
</script>
I tried to the result into a PHP variable, which does echo out nicely, and also tried the "hidden div" method to later extract it into a JS function, you can see both attempts here (both which print the correct follower number on a page):
<?php $goCount = "<span class='googleFollowerCount'></span>";
echo "goCount is: $goCount";
?>
<div id="googlePlusCountHiddenDiv"><?php echo $goCount; ?></div>
And here's the problem, I can't get that number into this JS function (I made an alert, and it returns NaN):
var goCount = parseInt($("#googlePlusCountHiddenDiv").text());
alert(goCount);
$({someValue: 0}).animate({someValue: goCount}, {
duration: 3000,
easing: 'swing',
step: function () {
$('#googlePlusCount').text(commaSeparateNumber(Math.round(this.someValue)));
},
complete:function(){
$('#googlePlusCount').text(commaSeparateNumber(Math.round(this.someValue)));
}
});
The whole seems to be going into the JS code, when what I want is the number that prints on the screen.
Any help is greatly appreciated. Thanks!!
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] />"
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;
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>
i'm creating a gallery which is loaded from a directory. first im creating a div tag for each album folder in the directory. then im using jquery ajax to get the folder name that was clicked and create div tags for each image in that folder. im sending the id of the folder to an external php page to grab the file paths for the images. im not sure how to output actual html. quite new to ajax/php coding so explanations are helpful.
jquery ajax:
var jq=$.noConflict();
jq(document).ready(function(){
jq(".album-select").click(function(event){
var id=event.target.id;
jq.ajax({
type: "POST",
url: "image_loader.php",
data: {phpid:id},
success: function(data){
jq('#mydiv').html("");
jq('#mydiv').append(data);
}
});
image_loader.php
<?php
if (isset($_POST['phpid'])) {
$album_fill = $_POST['phpid'];
}
$dir = 'images';
$slash = '/';
$dir_image = "$dir$slash$album_fill";
$dir_contents = scandir($dir_image);
foreach($dir_contents as $file){
if($file !== '.' && $file !== '..'){
$dir_imagepath = "$dir_image$slash$file";
echo '<div style="position:absolute; width:100px; height:100px; top:1100px; left:500px;">';
echo '<img src="',$dir_imagepath,'">';
echo '</div>';
}}?>
first of all change your success function as follows:
success: function(data){
$('#mydiv').html(data);
}
secondly, make sure your ajax call is returning an HTML page.
Take this
jq('#mydiv').html("");
jq('#mydiv').append(data);
And make it this
jq('#mydiv').html(data);