The rewritten title is: Using PHP buttons combined with jQuery and POST methods to get return values
P粉738821035
2023-09-05 08:42:27
<p>I have a simple form to get usernames and want to achieve the following: </p>
<ul>
<li>When the user clicks the button, the button will be disabled to prevent multiple clicks (in real cases it may take a few seconds to process all the data, such as calling API, writing to the database, etc.);</li>
<li>After click, a new POST request needs to occur in order to capture $_POST['username'] in PHP and process the request further. </li>
</ul>
<p>How to achieve this goal? </p>
<p>The code is as follows, but it does not work as expected: </p>
<pre class="brush:php;toolbar:false;"><?php
session_start();
// Process the form data when the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST['submit-button'])) {
$uname=$_POST['username'];
header('Location: success.php');
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>My Form</title>
</head>
<body>
<form id="your_form_id" action="test4.php" method="post">
<p><label>Username</label>
<input id="username" type="text" name="username" value="" autofocus/></p>
<input type="submit" id="submit-button" name="submit" value="Login" />
</form>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$("#submit-button").on("click", function(e){
document.getElementById("submit-button").disabled = true;
document.getElementById("submit-button").value="Processing, please wait...";
document.getElementById("your_form_id").submit();
});
</script>
</body>
</html></pre></p>
You are using the JQuery library, but you are using native JavaScript commands to handle buttons and submit(). Either you go all Pure JS, or you go all JQuery.
The code below only uses JQuery. Additionally, I replaced submit with a button.
. Finally, buttons are not POSTed, so if you need to test, do it on the input field.
Below is a code containing the elements I just mentioned that should help you.
To achieve this, the following principles can be used:
test-a.php:
test-b.php:
test-c.php: