I'm trying to execute a PHP function in the same page after the user enters a text and presses a submit button.
在用户输入文本并按下submit按钮后,我尝试在同一个页面中执行PHP函数。
The first I think of is using forms. When the user submits a form, a PHP function will be executed in the same page. The user will not be directed to another page. The processing will be done and displayed in the same page (without reloading)
我首先想到的是使用表单。当用户提交表单时,PHP函数将在同一个页面中执行。用户不会被导向另一个页面。处理过程将在同一个页面中完成并显示(不重新加载)
Here is what I reach to:
以下是我想说的:
In test.php file:
在测试。php文件:
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" onclick="test()" />
</form>
The PHP code [ test()
function ] is in the same file also:
PHP代码[test()函数]也在同一个文件中:
<?php
function test() {
echo $_POST["user"]; //just an example of processing
}
?>
However, I still getting a problem! Any one have an idea?
然而,我还是有问题!有人知道吗?
10 个解决方案
#1
26
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.
这不能按照你所说的方式来做。PHP是服务器端,而表单存在于客户端。如果您不想刷新页面,那么需要使用Javascript和/或AJAX。
test.php
test.php
<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 JS function in the result
variable back on test.php
and (in this case) shown in an alert box.
它将调用getResult。php并将序列化的表单传递给它,以便php可以读取这些值。getResult任何东西。php echos将返回到测试结果变量中的JS函数。php和(在本例中)显示在一个警告框中。
getResult.php
getResult.php
<?php
echo "The name you typed is: " . $_REQUEST['user'];
?>
NOTE This example uses jQuery, a 3rd-party Javascript Wrapper. I suggest you first develop a better understanding of how these web technologies work together before complicating things for yourself further.
注意,这个示例使用jQuery,这是一个第三方Javascript包装器。我建议您首先对这些web技术如何协同工作有一个更好的理解,然后再进一步使事情复杂化。
#2
9
You have a big misunderstanding of how the web works.
你对网络的工作方式有很大的误解。
Basically, things happen this way:
基本上,事情是这样发生的:
- User (well, the browser) requests
test.php
from your server - 用户(浏览器)请求测试。php从您的服务器
- On the server,
test.php
runs, everything inside is executed, and a resulting HTML page (which includes your form) will be sent back to browser - 在服务器上,测试。php运行,内部的所有内容都被执行,生成的HTML页面(包括表单)将被发送回浏览器。
- The browser displays the form, the user can interact with it.
- 浏览器显示表单,用户可以与它交互。
- The user submits the form (to the URL defined in
action
, 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. - 用户提交表单(提交到活动中定义的URL,在本例中是相同的文件),所以一切都从开始开始(除了表单中的数据也将被发送)。对服务器的新请求、PHP运行等等。这意味着页面将被刷新。
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.
您试图从onclick属性调用test()。这种技术用于运行客户端脚本,在大多数情况下是Javascript(代码将在用户的浏览器上运行)。这与PHP(服务器端PHP)无关,它驻留在服务器上,只有在收到请求时才会运行。请阅读客户端和服务器端代码。
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).
如果您想要在不引起页面刷新的情况下做一些事情,您必须使用Javascript在后台向服务器发送请求,让PHP执行它需要做的事情,并从它接收答案。这种技术基本上被称为AJAX,您可以使用谷歌(类似于Mozilla的惊人教程)在其上找到很多很棒的资源。
#3
6
Without reloading, using html y php only it is not posible but this can be very similar to what you want, but you have to reload:
不重新加载,只使用html y php是不可能的,但是这可能非常类似于您想要的,但是您必须重新加载:
<?php
function test() {
echo $_POST["user"];
}
if (isset($_POST[])){ //If it is the first time, it does nothing
test();
}
?>
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" onclick="test()" />
</form>
#4
5
Here is a full php script to do what you're describing, though pointless. You need to read up on server-side vs. client-side. PHP can't run on the client-side, you have to use javascript to interact with the server, or put up with a page refresh. If you can't understand that, there is no way you'll be able to use my code (or anyone else's) to your benefit.
这里有一个完整的php脚本,可以执行您所描述的,尽管毫无意义。您需要阅读服务器端和客户端。PHP不能在客户端运行,您必须使用javascript与服务器交互,或者使用页面刷新。如果您不能理解这一点,那么您将无法使用我的代码(或其他任何人的代码)对您有利。
The following code performs AJAX call without jQuery, and calls the same script to stream XML to the AJAX. It then inserts your username and a <br/>
in a div below the user box.
下面的代码在没有jQuery的情况下执行AJAX调用,并调用相同的脚本将XML流到AJAX。然后在用户框下面的div中插入用户名和
。
Please go back to learning the basics before trying to pursue something as advanced as AJAX. You'll only be confusing yourself in the end and potentially wasting other people's money.
在尝试像AJAX这样先进的东西之前,请回过头来学习基础知识。你最终只会让自己迷惑,并有可能浪费别人的钱。
<?php
function test() {
header("Content-Type: text/xml");
echo "<?xml version=\"1.0\" standalone=\"yes\"?><user>".$_GET["user"]."</user>"; //output an xml document.
}
if(isset($_GET["user"])){
test();
} else {
?><html>
<head>
<title>Test</title>
<script type="text/javascript">
function do_ajax() {
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var xmlDoc = xmlhttp.responseXML;
data=xmlDoc.getElementsByTagName("user")[0].childNodes[0].nodeValue;
mydiv = document.getElementById("Test");
mydiv.appendChild(document.createTextNode(data));
mydiv.appendChild(document.createElement("br"));
}
}
xmlhttp.open("GET","<?php echo $_SERVER["PHP_SELF"]; ?>?user="+document.getElementById('username').value,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" id="username"/>
<input type="button" value="submit" onclick="do_ajax()" />
</form>
<div id="Test"></div>
</body>
</html><?php } ?>
#5
5
Use SAJAX or switch to JavaScript
使用SAJAX或切换到JavaScript。
Sajax is an open source tool to make programming websites using the Ajax framework — also known as XMLHTTPRequest or remote scripting — as easy as possible. Sajax makes it easy to call PHP, Perl or Python functions from your webpages via JavaScript without performing a browser refresh.
Sajax是一个开源工具,可以让使用Ajax框架(也称为XMLHTTPRequest或远程脚本)的编程网站尽可能简单。Sajax可以轻松地通过JavaScript从web页面调用PHP、Perl或Python函数,而无需执行浏览器刷新。
#6
3
That's now how PHP works. test()
will execute when the page is loaded, not when the submit button is clicked.
这就是PHP的工作原理。test()将在加载页面时执行,而不是在单击submit按钮时执行。
To do this sort of thing, you have to have the onclick
attribute do an AJAX call to a PHP file.
要执行这种操作,必须让onclick属性对PHP文件执行AJAX调用。
#7
3
in case you don't want to use Ajax , and want your page to reload .
如果您不想使用Ajax,并希望页面重新加载。
<?php
if(isset($_POST['user']) {
echo $_POST["user"]; //just an example of processing
}
?>
#8
2
You can submit the form without refreshing the page, but to my knowledge it is impossible without using a JavaScript/AJAX Call to a PHP Script on your server. The following example uses the jQuery JavaScript Library.
您可以在不刷新页面的情况下提交表单,但据我所知,不使用JavaScript/AJAX调用服务器上的PHP脚本是不可能的。下面的示例使用jQuery JavaScript库。
HTML
HTML
<form method = 'post' action = '' id = 'theForm'>
...
</form>
Java Script
Java脚本
$(function() {
$("#theForm").submit(function() {
var data = "a=5&b=6&c=7";
$.ajax({
url: "path/to/php/file.php",
data: data,
success: function(html) {
.. anything you want to do upon success here ..
alert(html); // alert the output from the PHP Script
}
});
return false;
});
});
Upon Submission the anonymous Javascript function will be called, which simply sends a request to your PHP File (which will need to be in a separate file, btw). The data
above needs to be URL Encoded query string that you want to send to the PHP File (basically all of the current values of the form fields). These will appear to your server-side PHP Script in the $_GET
super global. An example is below.
提交后将调用匿名Javascript函数,该函数只向PHP文件发送一个请求(顺便说一下,这个请求需要放在一个单独的文件中)。上面的数据需要是您想要发送给PHP文件的URL编码的查询字符串(基本上是表单字段的所有当前值)。这些将出现在$_GET超级全局变量的服务器端PHP脚本中。下面就是一个例子。
var data = "a=5&b=6&c=7";
If that is your data string, then the PHP Script will see this as:
如果这是您的数据字符串,那么PHP脚本将看到如下内容:
echo($_GET['a']); // 5
echo($_GET['b']); // 6
echo($_GET['c']); // 7
You however will need to construct the data from the form fields as they exist for your form, such as:
但是,您需要从表单字段中构造数据,因为表单字段存在于您的表单中,例如:
var data = "user=" + $("#user").val();
(You will need to tag each form field with an 'id', the above id is 'user'.)
(您需要用“id”标记每个表单字段,上面的id是“user”。)
After the PHP Script Runs, the success
function is called, and any and all output produced by the PHP script will be stored in the variable html
.
运行PHP脚本之后,将调用success函数,PHP脚本生成的所有输出都将存储在变量html中。
...
success: function(html) {
alert(html);
}
...
#9
2
Take a look at this example:
看看这个例子:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
#10
1
This is the better way that I use to create submit without loading in a form.
这是我用来创建提交而不加载表单的更好方法。
You can use some CSS to stylise the iframe the way you want.
您可以使用一些CSS来按您希望的方式样式化iframe。
A php result will be loaded into the iframe.
php结果将被加载到iframe中。
<form method="post" action="test.php" target="view">
<input type="text" name="anyname" palceholder="Enter your name"/>
<input type="submit" name="submit" value="submit"/>
</form>
<iframe name="view" frameborder="0" style="width:100%">
</iframe>
#1
26
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.
这不能按照你所说的方式来做。PHP是服务器端,而表单存在于客户端。如果您不想刷新页面,那么需要使用Javascript和/或AJAX。
test.php
test.php
<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 JS function in the result
variable back on test.php
and (in this case) shown in an alert box.
它将调用getResult。php并将序列化的表单传递给它,以便php可以读取这些值。getResult任何东西。php echos将返回到测试结果变量中的JS函数。php和(在本例中)显示在一个警告框中。
getResult.php
getResult.php
<?php
echo "The name you typed is: " . $_REQUEST['user'];
?>
NOTE This example uses jQuery, a 3rd-party Javascript Wrapper. I suggest you first develop a better understanding of how these web technologies work together before complicating things for yourself further.
注意,这个示例使用jQuery,这是一个第三方Javascript包装器。我建议您首先对这些web技术如何协同工作有一个更好的理解,然后再进一步使事情复杂化。
#2
9
You have a big misunderstanding of how the web works.
你对网络的工作方式有很大的误解。
Basically, things happen this way:
基本上,事情是这样发生的:
- User (well, the browser) requests
test.php
from your server - 用户(浏览器)请求测试。php从您的服务器
- On the server,
test.php
runs, everything inside is executed, and a resulting HTML page (which includes your form) will be sent back to browser - 在服务器上,测试。php运行,内部的所有内容都被执行,生成的HTML页面(包括表单)将被发送回浏览器。
- The browser displays the form, the user can interact with it.
- 浏览器显示表单,用户可以与它交互。
- The user submits the form (to the URL defined in
action
, 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. - 用户提交表单(提交到活动中定义的URL,在本例中是相同的文件),所以一切都从开始开始(除了表单中的数据也将被发送)。对服务器的新请求、PHP运行等等。这意味着页面将被刷新。
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.
您试图从onclick属性调用test()。这种技术用于运行客户端脚本,在大多数情况下是Javascript(代码将在用户的浏览器上运行)。这与PHP(服务器端PHP)无关,它驻留在服务器上,只有在收到请求时才会运行。请阅读客户端和服务器端代码。
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).
如果您想要在不引起页面刷新的情况下做一些事情,您必须使用Javascript在后台向服务器发送请求,让PHP执行它需要做的事情,并从它接收答案。这种技术基本上被称为AJAX,您可以使用谷歌(类似于Mozilla的惊人教程)在其上找到很多很棒的资源。
#3
6
Without reloading, using html y php only it is not posible but this can be very similar to what you want, but you have to reload:
不重新加载,只使用html y php是不可能的,但是这可能非常类似于您想要的,但是您必须重新加载:
<?php
function test() {
echo $_POST["user"];
}
if (isset($_POST[])){ //If it is the first time, it does nothing
test();
}
?>
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" onclick="test()" />
</form>
#4
5
Here is a full php script to do what you're describing, though pointless. You need to read up on server-side vs. client-side. PHP can't run on the client-side, you have to use javascript to interact with the server, or put up with a page refresh. If you can't understand that, there is no way you'll be able to use my code (or anyone else's) to your benefit.
这里有一个完整的php脚本,可以执行您所描述的,尽管毫无意义。您需要阅读服务器端和客户端。PHP不能在客户端运行,您必须使用javascript与服务器交互,或者使用页面刷新。如果您不能理解这一点,那么您将无法使用我的代码(或其他任何人的代码)对您有利。
The following code performs AJAX call without jQuery, and calls the same script to stream XML to the AJAX. It then inserts your username and a <br/>
in a div below the user box.
下面的代码在没有jQuery的情况下执行AJAX调用,并调用相同的脚本将XML流到AJAX。然后在用户框下面的div中插入用户名和
。
Please go back to learning the basics before trying to pursue something as advanced as AJAX. You'll only be confusing yourself in the end and potentially wasting other people's money.
在尝试像AJAX这样先进的东西之前,请回过头来学习基础知识。你最终只会让自己迷惑,并有可能浪费别人的钱。
<?php
function test() {
header("Content-Type: text/xml");
echo "<?xml version=\"1.0\" standalone=\"yes\"?><user>".$_GET["user"]."</user>"; //output an xml document.
}
if(isset($_GET["user"])){
test();
} else {
?><html>
<head>
<title>Test</title>
<script type="text/javascript">
function do_ajax() {
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var xmlDoc = xmlhttp.responseXML;
data=xmlDoc.getElementsByTagName("user")[0].childNodes[0].nodeValue;
mydiv = document.getElementById("Test");
mydiv.appendChild(document.createTextNode(data));
mydiv.appendChild(document.createElement("br"));
}
}
xmlhttp.open("GET","<?php echo $_SERVER["PHP_SELF"]; ?>?user="+document.getElementById('username').value,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" id="username"/>
<input type="button" value="submit" onclick="do_ajax()" />
</form>
<div id="Test"></div>
</body>
</html><?php } ?>
#5
5
Use SAJAX or switch to JavaScript
使用SAJAX或切换到JavaScript。
Sajax is an open source tool to make programming websites using the Ajax framework — also known as XMLHTTPRequest or remote scripting — as easy as possible. Sajax makes it easy to call PHP, Perl or Python functions from your webpages via JavaScript without performing a browser refresh.
Sajax是一个开源工具,可以让使用Ajax框架(也称为XMLHTTPRequest或远程脚本)的编程网站尽可能简单。Sajax可以轻松地通过JavaScript从web页面调用PHP、Perl或Python函数,而无需执行浏览器刷新。
#6
3
That's now how PHP works. test()
will execute when the page is loaded, not when the submit button is clicked.
这就是PHP的工作原理。test()将在加载页面时执行,而不是在单击submit按钮时执行。
To do this sort of thing, you have to have the onclick
attribute do an AJAX call to a PHP file.
要执行这种操作,必须让onclick属性对PHP文件执行AJAX调用。
#7
3
in case you don't want to use Ajax , and want your page to reload .
如果您不想使用Ajax,并希望页面重新加载。
<?php
if(isset($_POST['user']) {
echo $_POST["user"]; //just an example of processing
}
?>
#8
2
You can submit the form without refreshing the page, but to my knowledge it is impossible without using a JavaScript/AJAX Call to a PHP Script on your server. The following example uses the jQuery JavaScript Library.
您可以在不刷新页面的情况下提交表单,但据我所知,不使用JavaScript/AJAX调用服务器上的PHP脚本是不可能的。下面的示例使用jQuery JavaScript库。
HTML
HTML
<form method = 'post' action = '' id = 'theForm'>
...
</form>
Java Script
Java脚本
$(function() {
$("#theForm").submit(function() {
var data = "a=5&b=6&c=7";
$.ajax({
url: "path/to/php/file.php",
data: data,
success: function(html) {
.. anything you want to do upon success here ..
alert(html); // alert the output from the PHP Script
}
});
return false;
});
});
Upon Submission the anonymous Javascript function will be called, which simply sends a request to your PHP File (which will need to be in a separate file, btw). The data
above needs to be URL Encoded query string that you want to send to the PHP File (basically all of the current values of the form fields). These will appear to your server-side PHP Script in the $_GET
super global. An example is below.
提交后将调用匿名Javascript函数,该函数只向PHP文件发送一个请求(顺便说一下,这个请求需要放在一个单独的文件中)。上面的数据需要是您想要发送给PHP文件的URL编码的查询字符串(基本上是表单字段的所有当前值)。这些将出现在$_GET超级全局变量的服务器端PHP脚本中。下面就是一个例子。
var data = "a=5&b=6&c=7";
If that is your data string, then the PHP Script will see this as:
如果这是您的数据字符串,那么PHP脚本将看到如下内容:
echo($_GET['a']); // 5
echo($_GET['b']); // 6
echo($_GET['c']); // 7
You however will need to construct the data from the form fields as they exist for your form, such as:
但是,您需要从表单字段中构造数据,因为表单字段存在于您的表单中,例如:
var data = "user=" + $("#user").val();
(You will need to tag each form field with an 'id', the above id is 'user'.)
(您需要用“id”标记每个表单字段,上面的id是“user”。)
After the PHP Script Runs, the success
function is called, and any and all output produced by the PHP script will be stored in the variable html
.
运行PHP脚本之后,将调用success函数,PHP脚本生成的所有输出都将存储在变量html中。
...
success: function(html) {
alert(html);
}
...
#9
2
Take a look at this example:
看看这个例子:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
#10
1
This is the better way that I use to create submit without loading in a form.
这是我用来创建提交而不加载表单的更好方法。
You can use some CSS to stylise the iframe the way you want.
您可以使用一些CSS来按您希望的方式样式化iframe。
A php result will be loaded into the iframe.
php结果将被加载到iframe中。
<form method="post" action="test.php" target="view">
<input type="text" name="anyname" palceholder="Enter your name"/>
<input type="submit" name="submit" value="submit"/>
</form>
<iframe name="view" frameborder="0" style="width:100%">
</iframe>