I\'m trying to execute a PHP function in the same page after the user enters a text and presses a submit button.
The first I think of is using forms. When the user s
This cannot be done in the fashion you are talking about. PHP is server-side while the form exists on the client-side. You will need to look into using JavaScript and/or Ajax if you don't want to refresh the page.
<form action="javascript:void(0);" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
$("form").submit(function(){
var str = $(this).serialize();
$.ajax('getResult.php', str, function(result){
alert(result); // The result variable will contain any text echoed by getResult.php
}
return(false);
});
</script>
It will call getResult.php
and pass the serialized form to it so the PHP can read those values. Anything getResult.php
echos will be returned to the JavaScript function in the result
variable back on test.php
and (in this case) shown in an alert box.
<?php
echo "The name you typed is: " . $_REQUEST['user'];
?>
NOTE
This example uses jQuery, a third-party JavaScript wrapper. I suggest you first develop a better understanding of how these web technologies work together before complicating things for yourself further.
That's now how PHP works. test()
will execute when the page is loaded, not when the submit button is clicked.
To do this sort of thing, you have to have the onclick
attribute do an AJAX call to a PHP file.
You have a big misunderstanding of how the web works.
Basically, things happen this way:
test.php
from your servertest.php
runs, everything inside is executed, and a resulting HTML page (which includes your form) will be sent back to browseraction
, which is the same file in this case), so everything starts from the beginning (except the data in the form will also be sent). New request to the server, PHP runs, etc. That means the page will be refreshed.You were trying to invoke test()
from your onclick
attribute. This technique is used to run a client-side script, which is in most cases Javascript (code will run on the user's browser). That has nothing to do with PHP, which is server-side, resides on your server and will only run if a request comes in. Please read Client-side Versus Server-side Coding for example.
If you want to do something without causing a page refresh, you have to use Javascript to send a request in the background to the server, let PHP do what it needs to do, and receive an answer from it. This technique is basically called AJAX, and you can find lots of great resources on it using Google (like Mozilla's amazing tutorial).
in case you don't want to use Ajax , and want your page to reload .
<?php
if(isset($_POST['user']) {
echo $_POST["user"]; //just an example of processing
}
?>