I have a quick question about PHP, say I am creating a form and there is a code snippet as follows:
<?php
if($_POST){
do something here
}else{
do something else
}
?>
When does this script run? I am more familiar with python and java, where code runs line by line, a brief explanation would be appreciated,
Thanks!
The script runs whenever the browser sends a request to the server with the URL scriptname.php. This is no different from if you use python or java to implement your server-side coding.
If the user simply goes to the URL via a link or entering it into the browser's address bar, there will not be any POST parameters. $_POST will be empty, and the do something here block of code will be executed.
But if the script is used as the action URL of an HTML form, the inputs will be in $_POST, and the do something else block will be executed.
This allows the same script to be used to display a form and also process the form data when the user submits it. This is a pretty common idiom in PHP webpage design.
One of the unique things about PHP is that it's embedded within a page of ordinary text (usually HTML, but it can actually be anything). When PHP is processing the file, anything that's outside <?php ... ?> is simply sent directly to the client. When it encounters <?php, it starts executing it as a script, until it reaches ?>. So if you have a PHP file like this:
<html>
<body>
<?php echo "This is some text"; ?>
</body>
</html>
it will put This is some text in the body of the resulting HTML document.
Related
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'
Let us consider the following html :
<!doctype html>
<html>
<body>
<form method="POST" action="submit.php">
<input name="name" placeholder="Enter your name">
<button type="submit">Submit</button>
</form>
</body>
Now to my understanding this code passes a list of arguments to a the php file which is mentioned in the action attribute of the method .
I understand that the code file is in the server system .
Now let us consider the code for submit.php as follow :
<?php
$name = $_REQUEST['name'];
?>
<!doctype html>
<html>
<body>
Hello <?php echo $name;?>
</body>
</html>
These codes are taken from an answer to my last question .
Now after the submit button is clicked . The client requests for a new page from the server .
I wanted to know what exactly is happening here . Does the server sends this code file to the browser and the php code is executed in the browser or submit.php , generates an html file according to the php code in it and that html file is sent to the client ?
Where is the code getting executed in the browser or in the server . With what I have read till now gives a feel that the code is being executed in the server but to be just sure .
Further , if the case is like the latter , i.e., the inputs are sent to server and the server based on the php code generates an html file that is sent back to the browser , then isn't it a bit inefficient in sending requests the server even for smaller changes ?
So what exactly is happening and where is the code getting executed ?
The PHP source is on the server and remains there. It is executed there, and the result (which is typically HTML, but can be anything else too), is sent as a response to the browser, so you got that right.
The advantage is that the PHP code itself is hidden to to user, and it can do advanced stuff like accessing files and databases which are hidden, and usually unaccessible directly for your website visitor.
The PHP code may be accidentally exposed when PHP is not set up properly. In that case, the code won't run but may be returned as plain text by accident. If you ever see PHP code in your browser, it's almost certainly due to an incorrect server set-up.
Even a small change should usually be done by the server. Theoretically it's inefficient to do those requests all the time, but in reality a request is not a big deal. If you only want to update the page itself, without doing anything special to the server, you could use JavaScript which can run in the browser as part of your page, and which can manipulate the loaded HTML document.
The whole process or execution life cycle can be explained in the following two steps:
Step-1:
Server-side PHP blocks enclosed in <?php ?> tags are executed and removed from the code base on the server on every request.
Step-2:
Client-side script and HTML tags left in step-1 are send for execution and display in the browser.
I hope the explanation is easily understandable now.
I am collecting data in a form which calls on a php file to put the data into mysql. It works fine, but after the data gets into the database, the browser just shows a blank page and in the browser input bar is the line
http://nameofmyste.net/mfb1.php
It is as though the HTML sent me to the php code where runs fine on the server then it just gets stuck, and stays there. How do I "get back" to my html script?
The call form action command looks like:
<form class="form-horizontal" role="form" action="mfb1.php" method="post" >
The php code exists in the file mfb1.php and works fine and just terminates with the standard closing "?> " at the end.
Thanks for your help.
Sorry for the delay in getting back to the question, and very sorry for my incorrect use of the forum, I am new and learning...
I have done some work since the original question and have created a very simple AJAX example that should work fine, but it doesn't. Here is the HTML file with the js function localform. It uses a synchronous AJAX call (3rd parameter set to "false") to invoke my php code, which is below as well.
It runs fine, I see the phrase "we made it" which replaces the "replace here" text on the html page, just like it is supposed to. But, within half a second, the "we made it" goes away and the "replace here" text shows up again.
It is as though the html code were running again form the top. The address in the browser bar, after the submit now reads
http://bruwptest.netne.net/Test%20Files/ajaxtester.html?
The question mark at the end is new.
Here is the code:
ajaxtester.php:
<?php
echo "we made it";
?>
ajaxtester.html:
<!DOCTYPE HTML>
<html>
<body>
<h1>AJAX Tester</h1>
<p>Echo here from the server: <span id="text">replace here</span></p>
<form onclick="localform()">
<button type="submit" >Submit</button>
</form>
<script>
function localform() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "ajaxtester.php",false);
xhttp.send();
document.getElementById("text").innerHTML = xhttp.responseText;
}
</script>
</body>
</html>
My question is why the html page is refreshing and overwriting the "we made it" that I just wrote there from the php?
It is as though the HTML sent me to the php code
Well, yes. That's what you specified:
<form class="form-horizontal" role="form" action="mfb1.php" method="post" >
<!-- right here ----^ -->
then it just gets stuck
Well, what does mfb1.php do? What output does it generate? If it doesn't render any HTML to the browser, then no HTML is rendered to the browser.
Or if there's an error and error reporting isn't turned on, there may be no valid output to render to the browser. Turn on error reporting during debugging, check your logs, etc.
You can, within that script, output any HTML that you like. Anything outside of <?php ?> tags is just sent directly to the client, so put any HTML that you want there.
Alternatively, at the logical completion of the script you could also redirect the user to another page:
header('Location: somePage.html');
This would return a response to the user's browser indicating that it should make a new request for somePage.html.
You have to send to client a redirect location to your original HTML page; at the end of your php script, write:
header( "Location: YourHtmlFileUrlHere" );
exit;
The exit command is not mandatory, if the command is at the end of script.
Please note: The header command fails if before in page there are ANY OUTPUT
I have a .php file that I'm trying to execute. It's referred to in the 'action' part of an html form.
For some reason when the form submits it opens the .php file in the browser as if it were an html page (a blank one).
The .php file doesn't have anything out of the ordinary in it, but I'm not sure it's getting to the point of executing it anyway.
My opening form tag looks like this: <form action="my_script.php" method="post">
What am I missing?...
In all likelihood your script is executing. By default, HTTP headers will be sent indicating that the script's content is HTML, hence that's how your browser will treat it. But if you don't actually send any output, it'll appear as a blank page.
If you want the form to do something but not open a new page, maybe you could use AJAX to submit the form data without leaving the page. Alternatively, you could just add at the end of the script
echo 'Finished :)';
so that you know it has gotten to the end, and presumably done something.
When you submit a form, your browser posts data to the URL specified by the action attribute, as part of the request for that page.
Your page at my_script.php should output some HTML.
If instead you see your PHP code when you view the source of this new page, then PHP is not configured to be parsed on the server.
euh... php
Use: http://www.apachefriends.org/en/index.html instead of opening a html file directly in your browser.
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