i am currently working on a class that generates diagrams as pictures with php. I want to load these pictures dynamically with jquery. How can i do that?? I wont have a real picture file, just the content of the file when i call it with ajax... And i cant simply define the php script as the src because i need to pass Post parameters to the picture...
EDIT:
Okay.. I think i have to explain it a bit further...
Here is the html code:
<div>
<img id="image" />
</div>
<input type="button" onclick="loadPicture();" />
When the button is pressed, some data should be send to the php script that generates the picture. A Callback function or something similar should now post the picture into the img- element.
Simply posting the Picture into the img tag doesnt work. The following code would work, but how can i add POST params??
<img src="<scriptname>.php" />
Http POST requests aren't meant to return resources. Why don't you use a GET request? The 'REST' way to do it will be to create the image with a POST request and then load it with a GET request. You need to define a URL mapping for your resources.
No people! You basically have 3 options as I see it.
Method 1 - Inline the image
Do what Brayn said, but data should be a base64 encoding of your image.
$("#div").html(data); // instead of this
$('#image').attr('src','data:image/gif;base64,'+data); // try something like this
But I don't like the idea of inlining the image or passing post data. Base64 might get a bit large for big images too.
Method 2 - Save the image
You can $.post the data like before, then save the image, and return the URL of the image.
Method 3 - Use GET
Modify your image-generating script to accept GET data. If you have a lot of data to pass, try compressing it somehow, or perhaps you can use SESSION variables.
I'm not very sure if I got it right from what you said but you could use the $.post() method that would return whatever you need through its callback. Something like this:
$.post("file.php",{param: val},function(data){
$("#div").html(data);
})
If you could explain further maybe we'll understand better. Hope this helps.
Is there any actual need to use AJAX / jQuery? Or are you simply putting it in because it's cool?
Here's what I would do:
if (isset($_POST['createImage'])){
// This means that the button was clicked
// Generate your image, and then display it:
}
// Regardless, you would now show your form
// That way if values were to be changed, the graphic can be recalculated.
This way, you achieve your desired output (the graphic loading depending on the form output) and a single click to generate that output.
Related
I have started learning php and I have a question.Let's say I have the following html code:
<p id='tobeChanged'>I wil be changed throughout the execution<p>
This paragraph is not static.Its content can be changed from the user with a button which will produce a random number and will replace the paragraphs html.
E.g. from
p id='tobeChanged'>I wil be changed throughout the execution<p>
to
<p id='tobeChanged'>42<p><!--changed with a button-->
Now my question.Is it possible to pass the new produced value to a php variable?If possible i would like a long explanation.
Also i would like not to use forms(if possible).
Thanks In advance
You need to fire an AJAX request on that button click, that will send that value to server making php to read it.
You can do something like this (you need to include jQuery on page):
$.post("/saveVariable.php",{randNum:randomNum},function(data){alert("Data saved successfully");})
At PHP end, you will get the value in
$_POST['randNum']
Maybe that will help.
I’m trying to store the content of a div to a variable.
Example:
<div class="anything">
<p>We don't know the content of this div</p>
</div>
I want to search for <div class="anything"> and store everything between opening and the end tag.
We also want to avoid using absolute pathnames, so that it only searches the current HTML/PHP file for this div where the code is present.
Is this possible with PHP, or is this only possible with JavaScript ?
PHP is not that intelligent. He doesn't even know what he says.
PHP is a server-side language. It has absolutely NO clue about what the DOM (ie. what is displayed in your browser's window) is when it delivers a page. Yeah I know, PHP rendered the DOM, so how could it not know what's in there?
Simply put, let's say that PHP doesn't have a memory of what he renders. He just knows that at one particular moment, he is delivering strings of characters, but that's all. He kind of doesn't get the big picture. The big picture goes to the client and is called the DOM. The server (PHP) forgets it immediately as he's rendering it.
Like a red fish.
To do that, you need JavaScript (which is on the client's computer, and therefore has complete access to the rendered DOM), or if you want PHP to do this, you have to retrieve an full-rendered page first.
So the only way to do what you want to do in PHP is to get your page printed, and only then you can retrieve it with an http request and parse it with, in your case, a library such as simpleHtmlDom.
Quick example on how to parse a rendered page with simpleHtmlDom:
Let's say you know that your page will be available at http://mypage.com/mypage.php
$html = file_get_html('http://mypage.com/mypage.php');
foreach($html->find('div.anything') as $element)
echo $element->src . '<br>';
you probably need a combination of those.
In your Javascript:
var content = document.getElementsByClassName("anything")[0].innerHTML();
document.getElementByID('formfield').value(content);
document.getElementByID('hiddenForm').submit();
In your HTML/PHP File:
<form id="hiddenForm" action="path/to/your/script">
<input type="hidden" name="formfield" value="" />
</form>
In the script you defined in the form action:
if(!empty($_POST)){
$content = $_POST['formfield'];
// DO something with the content;
}
Alternatively you could send the data via AJAX but I guess you are new to this stuff so you should start slowly :)
Cheers!
steve
You could use JS to take the .innerHTML from the elements you wan and store them in .value of some input fields of a form and then use a submit button to run the PHP form handling as normal. Use .readOnly to make the input fields uneditle.
I have this form and I would like to read the uploaded file and then fill out the form using this read information without refreshing the page.
For example the first word might be "Bob" and so I would want that to go in my input text "First_name." I've been trying to searching online for a way to do this using JQuery or Ajax but I can't seem to find a solution.
Can this be done using the two methods previously mentioned? If so and if not can someone point me to a link or to where I can learn how to do this? The instances I have found include where one uses JQuery to upload the file and display the size without refresh (which is not exactly what I want).
I have also found how one can use an iFrame but this again is not what I want. I suppose I could always just submit the part of the page containing the textfile related information and show the same form but with the filled out information. But I feel as if this is kind of sloppy and I want to know if there is a better way.
Thanks.
Firefox has a method to do this, the File and FileList API provide a way to get at the files selected by a file input element and have a text retrieval method.
A very basic example:
NB. Not all browsers support this code.
[I think Chrome, Firefox and Opera do at time of writing.]
HTML:
<form>
<input type="file" name="thefile" id="thefile" />
</form>
<div id="text"></div>
JS (using jQuery):
$(document).ready(function() {
$('#thefile').change(function(e) {
if (e.target.files != undefined) {
var reader = new FileReader();
reader.onload = function(e) {
$('#text').text(e.target.result);
};
reader.readAsText(e.target.files.item(0));
}
return false;
});
});
Demo: http://jsfiddle.net/FSc8y/2/
If the selected file was a CSV file, you could then process it directly in javascript.
.split() will be useful in that case to split lines and then fields.
the only way I know would be to submit the form to a hidden iframe. this will upload teh file without refreshing the page. you can then use any returned info using javascript. this is what they use for fake ajax style image uploads that let you preview an image before uploading. the truth is it already has been uploaded via a hidden iframe. unfortunately however iframes are not xhtml 1.0 compliant.
something like this article may help:
http://djpate.com/2009/05/24/form-submit-via-hidden-iframe-aka-fake-ajax/
The question you might ask is :
why should I use this method instead of real ajax ?
Well they’re is numereous answer to that but one good reason it that
is doesnt require any type of ajax libs and you can start using it
even if you never used ajax before.
So here it goes.
<form method=”post” action=”formProcess.php” target=”hiddenIFrame”>
<input type=”text” name=”test” /> </form>
<iframe style=”width:0px;height:0px;border:0px;” name=hiddenIFrame />
This is just a normal form but you’ll notice the target in the form
tag, this tells the form to submit in the iframe instead of the
current page.
It’s works exactly as the target attribut on the A tag.
Also the iframe is hidden from the user using
style=”width:0px;height:0px;border:0px;”
now the file formProcess.php is not different from your normal form
processing file but if you want do something on the main page you have
to use JS like that :
window.parent.whatEverYouWannaDoInParentForm();
You can also upload file with this method !
Please checkout the formphp for full example.
Cheers !
Nb : You will see the status bar acts like the page is reloading but
it’s really not.
Hi I just want to know what the best practice is for dynamically creating html. I can do it in two ways
Direct PHP
<div id='id-here'>
<?php
$user->id = $_GET['id'];
$user->displayUserInformation( );
?>
</div>
jQuery ajax(js script called on page load)
$.ajax({
type: 'GET',
url: 'inc/user_information.php',
data: 'user_id=user_id', //assuming user_id value was already set.
success: function(html)
{
$('#user_information').empty().html(html);
}
});
Note: This code doesn't exist and is purely for showing what I mean^^ I also know jQuery load, but prefer to use jQuery ajax for complex stuff.
Thanks!
The PHP method is certainly more reliable, as it doesn't require javascript in the client. For information that isn't expected during a page's lifetime, or indeed a user's session it also makes a lot more sense. I don't imagine the information on a user is likely to change that much during a page view.
However, if there is some data that's expected to change, say a post count or something, then use PHP to set the initial value, then use ajax to update it only when the value actually changes.
I wouldn't worry about which is faster... the difference would probably be negligible. But bear in mind that some users do have JavaScript turned off... if you want to support those users, it's worthwhile taking the extra effort to do it in PHP.
My rule is that if it can be done on the server, do it there. Then you can be absolutely sure of the results for all users.
u get it all wrong, first one is not a 'dynamically created html", user sent a request, PHP process it, and return the HTML, and your browser render it
2nd one is your browser already load HTML, and u try to use jquery to simulate another request of the same process of the 1st one
In your examples, if you show user info like this, method 1 will not require another data fetching from the server as in example 2 (2 HTTP requests total, 1 for original webpage, 1 for the ajax), so it is faster.
usually, generating static data inside a page like this (in example 1) is different from AJAX, where content is provided to the user, and only update with the new data using AJAX without updating the whole page's content.
Maybe what you mean is: should the data be provided together with the original webpage, or should it be left empty, and then use AJAX to fetch the data to display it. It would be better usually to provided data at first, instead of letting the user wait for another trip to the server to see the data.
I believe that loading from PHP as static loading would be better and more reliable. However loading from AJAX will push the results one time, not as static loading, data will be loaded in portions...
Along the same lines, which is faster within a php file. This is more for SEO and "best practice" than for actual user experience. I'm using wordpress, and I'm working within php files. Most of it is php, but I have four lines of html within the file. All are exactly the same. I could loop through the four lines with php, or copy and paste the four lines of html. I don't expect to ever change the code, so php doesn't seem to present any other benefits.
Here's my code:
HTML version (well mostly)
<img src="<?php echo get_bloginfo('template_directory').'/images/bracket.png';?>" class="bracket" />
<img src="<?php echo get_bloginfo('template_directory').'/images/bracket.png';?>" class="bracket" />
<img src="<?php echo get_bloginfo('template_directory').'/images/bracket.png';?>" class="bracket" />
<img src="<?php echo get_bloginfo('template_directory').'/images/bracket.png';?>" class="bracket" />
OR the php:
for($i=0;$i++;$i<4){ ?> //start loop, 4x
<img src="<?php echo get_bloginfo('template_directory').'/images/bracket.png';?>" />
//Image path using php
<?php } ?> // end loop
THANKS ALL!
I have a script which takes in html from the user as in full page html either from the user or grabs it via curl or from an email. The thing is that I have the html in a string but on the same page I need to show the htmnl in a separate iframe. I don't want to reput any database, curl or imap code in the page referenced by teh iframe at all - is there a way for me to show html passed into a url somehow? like as in a get variable .. the html can be huge here... sorry if it sounds weird.
You can put the grabbed html into a temp file and put the link to that temp file into the src="" of the iframe.
Create them using tempnam(), then create a small script that gets the (preferably obfuscated) filename and simply prints it out if it was really a temp file created by you.
Be careful! if it doesn't check the filename well, you are giving full read access to your server... Put the link to this script in the src of the iframe. You can also create temp files in the public folder of your www server, but I wouldn't want temp/garbage there.
(if i am not misunderstanding your question)
You could put the string in a textarea inside a form and submit the form ..
the receiving page would read the posted data and render it on the page..
I'm not quite sure what you want to do, put you could always post the string as a POST variable, no limitations on how long they can be.
You can encode pieces of HTML with urlencode which is automatically decoded when you retrieve it with $_GET or you can use e.g. base64_encode and base64_decode. The problem is that there are limits to $_GET and $_POST. Both can be set in your configuration settings, but sending large amounts of data via the URL is really not-done because that's not how it should be used.
But if I read your question correctly, you can fetch the HTML at the top of the page, and then load it into an iframe?
if ($_GET['url']) {
$html = file($_GET['url']);
}
if ($_POST['html']) {
$html = $_POST['html'];
}
And then include it:
<html>
..
<iframe ..><php echo $html; ?></iframe>
..
</html>