Loading php pages with jquery - php

Loading an external php file with jquery is actually easy. I simply use the load() event.
Like this:
$("#someelement").load('somepage.php');
Typically it's just fine, until I use the image manipulation functions.
Here's what I put inside somepage.php
<?php
$img = 'tmp/someimage.png';
$img = imagecreatefrompng($img);
header('Content-type: image/png');
imagepng($img);
?>
When somepage.php is loaded, I get messy code back. (which I'm not sure what it would be considered)
I'm pretty sure there's a limitation to loading complicated image functions, but I thought I'd ask if there's a workaround.

As #onteria_ pointed out, .load() isn't for image data. It's for HTML.
You will have to create an <img /> tag, set its src= attribute, and then append it to your element:
$('body').append($('<img id="someelement" />').attr('src', 'somepage.php'));

If you want to print an image, just append <img src="somepage.php" /> where you want with jQuery.
Since you are trying to load the file like a text, jQuery trying to get the contents of it. Loading an executed php file that echoes texts is one thing, printing images is another.

Related

Use PHP to prep SVG file for use in img tag data uri

I'm using PHP. I would like to use file_get_contents to get an .svg file, and convert it for use as a data uri in an image tag. Something along these lines:
Controller:
$mylogo = file_get_contents(FCPATH.'app/views/emails/images/mylogo.svg');
View:
<img src="data:image/svg+xml;utf8,<?= $mylogo ?>">
I need to convert it into something (base64?) as right now it is just dumping it in tags and all and though the image does appear, it makes a mess of the img tag surrounding it.
<svg> elements can be echoed directly onto a web page like any other element; there's no need to include it as an img src attribute. PHP's include can be used for this (ie. include('/path/to/image.svg')), amongst a myriad of other methods.
Alternatively, if for some reason you need to include the svg as an actual img tag, there's no need for file_get_contents or similar functions; an SVG can be linked as a source path like any other image type (ie. <image src="/path/to/image.svg">).
Solution
Controller
$encodedSVG = \rawurlencode(\str_replace(["\r", "\n"], ' ', \file_get_contents($path)));
View
<img src="data:image/svg+xml;utf8,<?= $encodedSVG ?>">
⚠️ Do not convert to base64
It's less efficient in CPU time and also makes longer requests in size!
Know more about why

PHP: Returning Data to a Web page

I have an application that returns data to a PHP/HTML file but the issue is it can call my application many times per page load:
An example HTML file with my calls only asking for images:
<img border="0" alt="" src="http://mydomain.com/test/index.php?element=1"></img>
</br>
<img border="0" alt="" src="http://mydomain.com/test/index.php?element=2"></img>
</br>
<img border="0" alt="" src="http://mydomain.com/test/index.php?element=3"></img>
</br>
This works fine every time and all of the images are returned, however my trouble starts when I want to return text/html.
The server side code works fine:
header('Content-type: text/html');
ob_start();
echo $filepath;
ob_flush();
ob_end_clean();
$filepath contains some text or HTML such as, "Check out our <strong>NEW</strong> offers!"
All I want is to return the HTML text and allow it to be embedded within the page so that if they want:
<h1>Check out our <strong>NEW</strong> offers!</h1>
or
<p>Check out our <strong>NEW</strong> offers!</p>
It will work fine.
The problem is, which HTML Tag should I use to call for the data in the same way I use <img> for images?
I have tried <object>, `
` etc... but these are no good as all I want is the raw HTML data returned.
Using the Javascript load() is not good as it relies on the web page builder creating a function call for every time they want to get data.
You can't do it with HTML, you could use jQuery + AJAX.
You have to use Ajax. you cannot do it in html.
You can output it with PHP and then if you update the file it will update site wide without making changes everywhere. Is there a reason you want to do it this way and not just insert the code manually? This could cause problems with the caching of your pages depending on how dynamic they are.
newOffers.php
<?php
echo '<h1>Check out our <strong>NEW</strong> offers!</h1>';
?>
Then in your site source:
<p>Blah blah blah...</p>
<?php include 'newOffers.php'; ?>
<p>Click our new offers link above</p>
You can use an <iframe> for this, but this is not really ideal as the resizing is not done automatically.
Alternatively you can indeed use Ajax to change the code.
Either way: think about your reason for wanting to include the HTML like this instead of just returning this html code with the original return?

Preloading pictures for refresh, cache

I have these two php variables: $img1src and $img2src, (them being PHP is irrelevant as you can echo a php variable anywhere) they both hold a URL of an image. I was wondering if I was able to preload these images, or cache them.
My goal is: when someone refreshes the page I want these pictures to instantly appear in a <img src >.
I'm not going to provide specific code, because I don't want to give you a fish, but rather show how google is a fishing pole.
I googled "php cache images tutorial" just to see what would come up. Below is a great resource.
http://dtbaker.com.au/random-bits/how-to-cache-images-generated-by-php.html
Can't get much better than that.
Caching an image isn't really a job for PHP. PHP should be used to decide whether or not to display it. (There are caching things you can do with PHP, but not in the same sense.) Essentially, what you want to do is make the clients browser request the second image. Once the browser gets the image, it should automatically send an "if-modified-by" parameter in the header. Next time you load the page, the response code should be 304 and your image should load instantly. You can choose from a variety of ways to do this. Load the image with javascript after the page has loaded (to prevent additional load time) or you can just include an image tag that is hidden on the page some where.
I also haven't tested it, but you might be able to send an ajax request to the image directly. I'm not sure if that way would cache it or not.
EDIT:
This isn't the most elegant solution, but it should get the idea across.
JS Example:
<?php
session_start();
if (!isset($_SESSION['graphic'])) $_SESSION['graphic'] = "http://www.tomsfreelance.com/laptop/DSC_0011.JPG";
else $_SESSION['graphic'] = "http://www.tomsfreelance.com/laptop/DSC_0012.JPG";
?>
<html>
<head>
<script>
function loadImage() {
document.getElementById('preload').style.backgroundImage = "url(http://www.tomsfreelance.com/laptop/DSC_0012.JPG)";
}
</script>
</head>
<body onload="loadImage();">
<div id="preload" style="display: none;"></div>
<img src="<?php echo $_SESSION['graphic'];?>">
</body>
</html>
Sure you can, try this javascript:
var image1 = new Image(), image2 = new Image();
image1.src = <?php echo $img1src; ?>;
image2.src = ?<php echo $img2src; ?>;
That should preload the image so when you append an img tag to the DOM the image should appear right away.
If your aim is to make less http requests overall: you can try CSS Sprites and/or Data Url methods of displaying these images. These methods will be the most effective when the images are smaller.

random images with background: linking to a random image php script - simpler and better way

I know there has to be a better way to do this.
Currently I have a php script which will generate a random image from a certain directory when called.
I have div's calling the background.php file in the stylesheet under the div's background setting
background:url(randomimagescript.php);
There are a lot of little div's on this page right now, all calling separate random image php scripts... is there a way I could use a variable when calling the file, so I can just use one script? I still need to have good styling control over the image, so i'm not sure if there is a better option than calling the script as a background image for a div.
If anyone has any ideas, let me know!
try this (it might not be optimal):
background:url("randomimagescript.php?folder=myfolder");
and in randomimagescript.php:
<?php
$folder = #_$REQUEST['folder'];
$url = "galleries/$folder/thumbs/image.jpg"; // ie, compose image
http_redirect($url); // go and find the image.
?>
It sounds a little crazy, but you could actually make your stylesheet be generated by PHP, and just fill in the blank, so to speak.
background:url(<? echo pickRandomImage(); ?>)
set the background for all divs once on the page using jquery
var image = <?echo randomimagescript.php?>
$("div").css('background', 'url('+ image+ ')');

How to embed a graph (jpgraph) in a web-page

I am using this script which is one of the examples provided by jpgraph itself. When I put this on a web-page (blank) by itself, it's drawing the graph. But when I embed the code in already existing web-page (with some content), it ain't drawing a graph.
GD is already enabled according to phpinfo(). Iam using jpgraph 3.5.0b1.
The problem is that you are mixing HTML/text output with image output.
Any time you have a PHP script generate graphical content you have to handle the output differently than normal HTML or text.
There are a few routes, I'll cover them briefly here.
Save the output to a file and use that filename in your HTML
//replace this line:
// Display the graph
//$graph->Stroke();
// with these lines:
// Default is PNG so use ".png" as suffix
$fileName = "/tmp/imagefile.png";
$graph->img->Stream($fileName);
.. then use $filename in an image tag, like this (for example):
print '<img src="'.$filename.'" />';
Create a standalone PHP script that will output the graphic
You can use the example script as-is, alone in a file called graph_render_script.php. Then, in your HTML, you use that script as a source:
<img src="graph_render_script.php" />
Output base-64 encoded data
Another route is to use base-64 encoded image data. This is relatively simple to do:
print '<img src="data:image/png;base64,'.base64_encode($graph->Stroke()).'" />';
As always, the documentation should be your guide!
Documentation
http://jpgraph.net/download/manuals/chunkhtml/ch05s05.html
base64_encode - http://php.net/manual/en/function.base64-encode.php
This worked for me:
putting the php code that generates the image in a file...Then on my html page I do this:
<img src="graph.php" >
embedding the graph inline is indeed possible. You'll have to use output buffering to capture the image data, then base64 encode that data, then use that base64-encoded string as the source in an <img>.
Try something like this:
$img = $graph->Stroke(_IMG_HANDLER);
ob_start();
imagepng($img);
$imageData = ob_get_contents();
ob_end_clean();
?><html>
<head>
<title>JpGraph Inline Image Example</title>
</head>
<body>
<h1>JpGraph Inline Image Example</h1>
<img src="data:image/png;base64,<?php echo(base64_encode($imageData)); ?>" />
</body>
</html>
ceejayoz made an excellent point in that this method is almost never what you want. I do not recommend embedding the image data like this unless you have a good reason to do so and understand the downsides, i.e. older browsers lack support for it, and the page size is dramatically increased (not only from the image data but the fact the image data is base64 encoded, which balloons the length). I've used this method in the field myself on a project last year, but it was only because the client refused to make a second request for the image.
But when I embed the code in already existing web-page (with some content), it ain't drawing a graph.
You can't do that - you can't output an image as raw binary data within a page.
You need to put the code that generates the graph in a separate file, and use an image tag.
<img src="path/to/jpgraph/chart.php" />
The graph needs to be on its own page, you can't embed it. It outputs a raw JPG and you need to have no other content sent and have the proper headers to tell the browser it's a JPG. To embed the graph you'd make a different page called stats.php for example, and on that page you'd make an image tag pointing to the stand alone graph.
<img src=graph.php>
I've had this problem many times, I've noticed it happens when you have require() or include() in your Chart's script and those scripts have Data Base connections or special configurations.
I've solved this problem separating the data retrieving and the Chart drawing, passing parameters to the script or using SESSIONS to get the values.
Example of Embed image Chart in your PHP or HTML file:
<img src="linear_graph_customer.php?values=1,2,3,4|1,2,3,4|1,2,3,4&title=CHART&width=500&height=300" width="500" height="300" class="img" />
Regards.

Categories