Changed php code with $(#selector).html doesn't execute, [duplicate] - php

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("&lt?php include_once('resources/UberGallery.php'); $gallery = UberGallery::init()->createGallery('img/gallerij/'); ?&gt");
})
});
I use the &lt and &gt, 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:
"&lt?php include_once('resources/UberGallery.php'); $gallery = UberGallery::init()->createGallery('img/gallerij/'); ?&gt"
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());
})
});

Related

Loading PHP function using jQuery onclick

I am trying to hide our mailing address on our website, until someone cliks a button to "load" the address. I am doing it like follows:
Homepage.php:
<button onclick="test()"> Click </button>
<div> </div>
<script>
function test(){
$.ajax({url:"address.php", success:function(result){
$("div").text(result);}
})
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
Address.php:
<?php
function php_func(){
echo '<span><?php echo $address; ?></span>';
}
php_func();
?>
This works in echoing the text onto homepage.php, but it's not loading the PHP function. Just showing the function as text as seen here:
I tried $("div").write(result);} and it won't even load.
$address is already defined elsewhere. Any tips?
You're trying to write code which outputs code which outputs the address. Why? You're already in the context of outputting something from the PHP code:
echo "something...";
If what you want to output is the value of $address then just output that:
echo "<span>$address</span>";
I suspect the reason you did it that way is because you're expecting the currently loaded page to parse and execute that PHP code. This is a fundamental misunderstanding of how these technologies work. The PHP code for that page executed once, on the server, and delivered the resulting HTML/CSS/JavaScript to the client.
The AJAX operation is making a new, separate request to another PHP resource which will execute on the server and output back to the client. In this case it's just outputting a string value, which the client-side JavaScript code will then write to an element on the page:
$("div").text(result);
(This is a good opportunity for you to use your browser's debugging tools and observe the AJAX request/result in the network tab, to see what's actually being sent/received. At no point should actual PHP code be visible to the browser. All of that is executed on the server.)
The reason this is important is because, if this is the case, then you are likely misunderstanding where $address is defined. If it's defined in the PHP script which rendered the page you're looking at, that doesn't mean it's defined in address.php. If the code you're showing us for address.php is the entirety of that page then $address is not defined.
So you'll need to define $address on that page.
After having said all of that... You might find it much easier not to involve AJAX for this at all in the first place. Just output the address to the page but style the <span> to not be visible. Then when the user clicks the button, make it visible. No need for the complexity of an entirely new HTTP request:
$('button').click(function () {
$('span').show();
});
span {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Click</button>
<span>this is the address</span>
You don't use <?php echo inside strings; that's only used when you're in a section of the script that's outputting literal text, not executing PHP code.
If you're in PHP code doing echo, you use variable substitution or concatenation.
<?php
function php_func(){
echo "<span>$address</span>";
}
php_func();
?>
You'll need additional code to set the $address variable; I assume you just left that out for simplification in the question.
<?php
function php_func(){
echo '<span>' . $address .'</span>';
}
php_func();
?>
this should work, u can't use 'echo' and inside echo open 'php' tag to use again.... more another 'echo'

Find and store all innerhtml of div to php variable

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.

loading two php or html page in two iframe by using one link at the same time

main page; index.php
There are two iframe in main page as
iframe name= topifrm
iframe name= content
I want to click on link "Education", then the following action should happen:
load topindex.php page to the topifrm and at the same time
load education.php page to the content
or
if you kindly please send me how do I access to php variable, say "$edu_id" in education.php from topindex.php page..
I have to say that there a lot of problems in what you are requesting. For a first, don't use IFrames. They were used like that ages ago and thankfully, things like ajax arrived.
The other problem is :
if you kindly please send me how do I access to php variable, say
"$edu_id" in education.php from topindex.php page..
Have in mind that PHP scripts are executed on the server and not in the browser. For that reason, whatever you see in the browser is a strict html file. To make it clear, you can't have access to the php variables from the browser. But it's not the end! Because many people do what you're trying to do but in a better way.
Let say you index.php that return this:
<html>
<head><title></title></body>
<body>
<div id="menu">
<ul>
<li><a data-phpid="education">Education</a></li>
</ul>
</div>
<div id="container"></div>
</body>
</html>
You'll need some javascript because without javascript, it's not really possible to do it correctly with iframes. With iframes, you can't really just get "data" or catch exceptions if the page fails to load.
I'll be using jQuery as everyone uses it and it might be easier to understand because it's not a so bad library. Put this is a script tags after you linked jquery and it should work.
$(function () {
// this will get executed when document is ready
$('#container').load("/secondframe.php");
$('#menu a').click(function() {
var pageid = $(this).data('phpid');
$("#container").load("/secondframe.php?phpid=" + pageid);
});
});
That said, it should work, in your php script you'll be checking for $_GET['pageid'] to get the id you just sent as "get" params.
But If I were you, I wouldn't use load but instead serialize everything to json, pass the json to a Javacript object to generate html on the browser instead of rendering html on the server. Leave php as it will never give you anything good but only nightmares.
Learn javascript! Learn it well don't use jQuery (jquery will prevent you from understanding how to write code in javascript). Learn python to write application server, learn ruby and don't restrict yourself to rails. And learn a lisp because real programmer program with lambda calculus!

How do I use jQuery to insert PHP tags through the DOM?

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

php custom forum error

i have a form, and i want to have it be limited at 10 characters minimum. that is no problem, but what i want to do is echo the error at the top of the page, which is being included, so i cant just do:
echo '<div class="error">Error</div>';
i want to have a designated div that is empty (will be on the included header page), but when there is an error it gets filled with the error text to output. anyone know how to do this not using sessions or cookies?
This is a clear use-case for javascript. PHP is strictly a server-side language; that is, the code you write is executed on the server and not the client. Javascript, on the other hand, is run inside the user's browser. So say you create a div like so: <div id="error_msg" />. Then you can write a snippet of javascript code that looks like this:
function display_error () {
var err_msg_div = getElementById("error_msg");
err_msg_div.innerHTML = "Error";
}
You would place this code in script tags at the top of your page inside the tags. More information on javascript form validation can be found here: http://www.w3schools.com/js/js_form_validation.asp
Hope this helps.
-tjw
Edit: if this isn't exactly what you're looking for, you might want to tag this post with 'javascript' to get more people who know about js form validation to answer the question.
<div id="error_msg" /></div>
<script>
function display_error (text) {
var err_msg_div = getElementById("error_msg");
err_msg_div.innerHTML = text;
}
display error('Error: your text here..');
</script>

Categories