PHP - $_POST
$_POST is a superglobal variable that holds an associative array of values submitted through an HTML form using the POST method. Here's a breakdown of its key aspects:
• HTML forms
• JavaScript HTTP requests
• $_POST in HTML Forms
$_POST is a superglobal variable in PHP that allows you to access data submitted by a form using the POST method. .
To demonstrate this, we start by creating a simple HTML form:
HTML form
<html> <body> <form method="POST" action="demo_request.php"> Name: <input type="text" name="fname"> <input type="submit"> </form> </body> </html>
When a user clicks the submit button, the form data is sent to a PHP file specified in the action attribute of the <form> tag.
In the action file we can use the $_POST variable to collect the value of the input field.
PHP file
$name = $_POST['fname']; echo $name;
In the example below we have put the HTML form and PHP code in the same PHP file.
We have also added some extra lines for security.
HTML form
<!DOCTYPE html> <html> <body> <form method="post" action="/tutorials/php/php-post.php"> Name: <input type="text" name="fname"> <input type="submit"> </form> <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { // collect value of input field $name = $_POST['fname']; if (empty($name)) { echo "Name is empty"; } else { echo $name; } } ?> </body> </html>
Output
Name:"--------"submit
• $_POST in JavaScript HTTP Requests
When sending a HTTP request in JavaScript, you can specify that the HTTP method is POST.
To demonstrate this we start by creating a JavaScript function containing a HTTP request:
JavaScript function
function myfunction() { const xhttp = new XMLHttpRequest(); xhttp.open("POST", "demo_phpfile.php"); xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhttp.onload = function() { document.getElementById("demo").innerHTML = this.responseText; } xhttp.send("fname=Mary"); } }
The code above will:
Intiate a HTTP request
Set the HTTP method to POST
Set a valid request header
Create a function to execute when the request is done
Send the HTTP request with a variable fname set to Mary