I have no idea how to do this. I want to insert php code into an image source through jquery.. but it is not working. Here is my code and help would be greatly appreciated!
JQUERY:
var mainId = $(this).attr('id');
$("#intabdiv img").attr('src', '<?=resize("../php/admin/portfolio/before/'+mainId+'",$settings)?>' );
HTML:
<div id="intabdiv">
<?php $settings = array('w'=>450,'h'=>450,'crop'=>true); ?>
<img src="" border="0" class="pic" />
</div>
</div>
It looks to me like you're trying to have the client browser execute PHP. That's not going to work for you. I'm not sure you have a completely clear idea of the separation between server and client, and what happens where.
Here's a simple model that you can use to think about where things occur:
User puts URL in browser and hits enter
Browser sends request to server
Server receives request and attempts to provide the resource requested
At this stage, if the file is a PHP file, any PHP instructions are executed. The end result of this, after all PHP is finished and done, is an HTML file, perhaps with some javascript.
The server sends this HTML file back to the browser.
The browser loads the HTML file, and executes any javascript, which can manipulate the HTML on the client side.
So, where does that leave us? You're attempting to take an image file that exists on the server, resize it, and display it to the end user. Presumably the "resize" function is one you have defined somewhere in your PHP code. I'll go on the assumption that you just need to do this once and have it show up for the user when the page loads.
In this case, what you need to do is something more like the following (all in the same file):
<?php
$settings = array('w'=>450,'h'=>450,'crop'=>true);
$imgsrc = resize("../php/admin/portfolio/before/imageid.jpg",$settings);
?>
<div id="intabdiv">
<img src="<?= $imgsrc; ?>" border="0" class="pic" />
</div>
... no javascript required. Obviously, imageid.jpg must be the actual filename of the image you're trying to access. If, instead, you're trying to have some user action trigger the access to the image, please provide more context for what you're trying to accomplish and a better answer can be given.
The problem is you set the html as having an ID, but jquery is using the selector as being a class.
So change it from:
$(".intabdiv img")...
To
$("#intabdiv img")...
Why not use something like jcrop? http://deepliquid.com/projects/Jcrop/demos.php
Related
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
So now i now this was a dumb question but does anyone now the best way to solve it without an ajax request, becaus I think it would be stupid to make a new file for just one line of code
I am making a gallery and I want two types of views one grid-view and a slide view. My slide and my grid view both work but they stand in different files. So I wrote a simple jquery function to load some php code into the html code. So that when I click a button the html code dissappears and there is php code. The jquery funtion works but the problem is that when the code is changed it doesn't recognise it as php code but just as a string.
This is what I see, you can see the text but it needs to execute that code:
Here is the jquery function:
$(document).ready(function(){
$("img.grid_icon").click(function() {
$(".werkvenster").html("<?php include_once('resources/UberGallery.php'); $gallery = UberGallery::init()->createGallery('img/gallerij/'); ?>");
})
});
I use the < and >, otherwise the browser sees it as php code it has to execute instead of seeing it as a string.
Here is the html code it has to be in:
<body>
<section class="werkvenster">
<img src="img/website/icon_grid.png" height="30px" class="grid_icon">
<div class="galerij" id="galerij">
</div>
<button class="omlaag" id="galerij_knop">Terug</button>
<button class="omhoog" id="galerij_knop">Verder</button>
</section>
</body>
So everything between the section tags with class "werkvenster" needs to be changed by
<?php include_once('resources/UberGallery.php'); $gallery = UberGallery::init()->createGallery('img/gallerij/'); ?>
When someone clicks on the grid icon.
Thanks a lot in advance and please don't mark this as a duplicate because I have been searching for over an hour to find an answer to this question.
It seems you need some clarification how PHP and JS work.
a) PHP-code is executed on the server-side. all of it. and nothing else
b) The output, completely free of PHP, is sent to the browser
c) JS-code is executed on the client-side. all of it. and nothing else
If you use JS to write PHP-code, it only happens inside the browser, which doesn't know what to do with it. and long after every bit of PHP-execution.
You do NOT write anything back to the server with this.
what you CAN do is to do an AJAX-request to a specific PHP file that returns your desired output. but you can't just mix JS and PHP like that. it just doesn't work.
edit: in response to your edit about how to solve the problem without using AJAX
to put it simply: not at all. you have to get the data from the server, the best way to do this is AJAX (it was made for this and nothing else) and on the server you have to generate the data somehow. and the cleanest way is a new file.
it doesn't recognise it as php code but just as a string
That's because it is a string:
"<?php include_once('resources/UberGallery.php'); $gallery = UberGallery::init()->createGallery('img/gallerij/'); ?>"
PHP doesn't run in the browser, it runs on the server. By the time the page is delivered to the browser, the PHP code has executed and completed and produced its output. PHP is no longer involved after that point.
If you want to execute code client-side, that's what JavaScript is for. If you need code to execute server-side, the browser will have to make a request to the server to make that happen. A page load, a form post, AJAX, etc. They all take the form of an HTTP request (potentially with some data sent to the server) which invokes a PHP script and receives that script's output as the response.
You could do what you are trying to do without ajax. You just have to create a hidden <section> that contains the php code (which you have to do on the server-side before it gets sent to the browser). And then in the browser, use jquery to get the contents from the hidden <section> (or just swap the sections)
Here is an example:
Server-side PHP:
<body>
<section class="werkvenster">
<img src="img/website/icon_grid.png" height="30px" class="grid_icon">
<div class="galerij" id="galerij">
</div>
<button class="omlaag" id="galerij_knop">Terug</button>
<button class="omhoog" id="galerij_knop">Verder</button>
</section>
<section id="hiddenStuff" style="display:none">
<?php include_once('resources/UberGallery.php'); $gallery = UberGallery::init()->createGallery('img/gallerij/'); ?>
</section>
</body>
jQuery:
$(document).ready(function(){
$("img.grid_icon").click(function() {
$(".werkvenster").html($("#hiddenStuff").html());
})
});
I am trying to upload a file a view the file on an iFrame but it is not working.
Here is what I have tried
jQuery('.file_upload1').change(function(){ jQuery('iframe').attr('src', jQuery(this).val()); $('iframe').attr('src', $('iframe').attr('src')); });
<label><input class="file_upload1" name="file_cover" type="file"></label>
<div>
<iframe src=""></iframe>
</div>
If this does not work, can I move the uploaded file to server directory so that the path becomes valid? How would I do this?
Apart from other problems and limitations of such solution, and specifically answering "why it does not work?" question:
The change event needs to be nested in ready function:
jQuery("document").ready(function() {
jQuery('.file_upload1').change(function() {
jQuery('iframe').attr('src', jQuery(this).val());
});
});
The src attribute of iframe must be a valid non-empty URL potentially surrounded by spaces. When selecting a file with input type file, in Windows the value will be something like c:\fakepath\file name goes.here, so before using as iframe source, you will have to rework it a little bit.
Regarding
I'm trying upload file and display it on iframe forcing it to reload
You don't need to force reload to achieve this. "Upload" means the page will be reloaded (well, unless upload is handled using AJAX, but it's not the case here I guess). In order to upload a file, the form must be submitted and the page needs to be reloaded. Once reloaded, you can easily construct the full path of the file and use it in iframe, something like:
<iframe src="<?php echo $file_full_url; ?>"></iframe>
But if you want to preview the file in iframe before uploading to server - it won't be possible due to security reasons. See this question for reference: How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?
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.
Here is what I'm trying to do...
$("div").prepend("<div id='comment-number'><?php the_comment_number(); ?></div>");
Is there some way to get this to work?
<div class="gallery-item">
<div class="comment-number"><!--?php echo htmlspecialchars(the_comment_number()); ?--></div>
</span>
<span class="gallery-icon">
<img src="http://mysite.com/test/wp-content/uploads/2011/06/fff-150x150.gif">
</span>
</div>
PHP is executed on the server, but JavaScript code (jQuery) is executed later, in the web browser. For that reason, PHP can produce JavaScript code, but JavaScript can't produce PHP code.
The <!--? in your posted output shows that something is filtering our your PHP code. So the problem isn't your PHP code, it's that you're not actually executing PHP code. If it's a .js file, PHP almost certainly can't be included.
If PHP were being evaluated (ex. if this were in a <script> tag in a .php file), this should produce valid JavaScript code that will do what you want:
$("div").prepend("<div id='comment-number'><?php echo htmlspecialchars(the_comment_number()); ?></div>");
1) php is SERVER side scripting
2) javascript is CLIENT side scripting (generally)
so this is what happens:
1) User opens up your page http://example/
2) Your CLIENT sends GET request to http://example/ server
3) Apache (given you run on it) captures the request, based on the server config approaches index.php (index.html, etc). If php is installed, your index.php will be parsed by mod_php module
<<<< this is where SERVER side scripting is activated
4) outcome of the parsing of index.php will be then transferred back to CLIENT
5) CLIENT will digest the outcome received by SERVER
6) If there are javascript calls, those are executed either immediately OR when document is loaded (based on approach)
That's it. Here normal request life ends.
NOW if you want your page to dynamically update some parts of it, here is how you do that:
1) Usually to update your page dynamically, you would use AJAX approach. When AJAX request is created, 2-7 happens again, but this time the caller is your ajax process and information which is received is sent back to that process to decided what to do with it.
Okay, some coding:
1) index.php
<!-- include jquery, etc //-->
<div id="comments"></div>
<script>
function fetch_comments(){
$.get("ajax.php", null, function(data)){
// this is called, when response from SERVER is received
$("#comments").prepend(data);
setTimeout("fetch_comments", 5000); // fetch again in 5 seconds
}
}
$(document).ready({
fetch_comments();
});
</script>
2) ajax.php
<?php
//fetch comments, return them for CLIENT
echo "<p>Comment on " . date("Y-m-d H:i:s") . "<br />Lorem Ipsum</p>";
This should help you understand the whole process. Did not test the code, but should be quite ok.
do a .ajax() query to PHP script that will provide you value of the_comment_number(); and put result to comment-number by $("#comment-number").prepend(result); on success event in ajax query.
Remebmer that PHP script have to have connection to database and pass to it all variables you need (like entity id, article id, page etc.). You can do it by GET or POST.
Request is sended by browser so session/cookies will be the same unless you changed it in current request.
PHP is executed on the server side so you cannot call it from javascript
You can try something like this which will render once the page loads
$("div").prepend("<div id='comment-number'>"+ <?php the_comment_number(); ?> +"</div>");
Couldn't you just add the value directly to the template instead of using javascriot? eg:
<div class="gallery-item">
<div class="comment-number"><?php echo (the_comment_number());?></div>
...
</div>
Also you have a </span> tag with out matching <span> tag in your example.
As already told, you can't produce or call php code from javascript directly(you need to make an ajax call or form submit). You need to make ajax call using jquery to fetch the comment number and then update it into div.
However, you may want to look at this library - http://www.phplivex.com/ .It may help you in doing things your way. It allows you to call user defined php functions in javascript using AJAX internally.
Reading through this disccussion and from what i understand you want to acheive.. You gotta figure how your page is served. If it is an .php file that is serving the content, then you wont need Javascript at all and could get your function call to work by adding the function between the div as so..
<div class="comment-number"><?php echo htmlspecialchars(the_comment_number()); ?></div>
Assuming you don't have access to the .php or if its a .html/htm page that serves the content then your only bet would be to use ajax. That is make an ajax call to a php file(on the same domain) that makes your function call and echos the comment no. The Ajax will retrieve the echo'd comment no. which you can append/prepend to the desired
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!