$_POST
contains an array of variables received via the HTTP POST method.
Variables can be sent using the HTTP POST method in two main ways:
An HTML form submits information via the HTTP POST method if the form’s method
attribute is set to “POST”.
To illustrate this, let’s create a simple HTML form:
HTML Form
<html> <form method="POST" action="demo_request.php"> </body> |
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 specified action file, we can use the $_POST variable to collect the values of the input fields.
PHP file
$name
|
In the example below, we have included both the HTML form and PHP code in the same PHP file.
Additionally, we have added some extra lines for security.
<html>
<?php $name = htmlspecialchars($_POST['fname']); ?>
</body> |
When sending an HTTP request in JavaScript, you can specify that the HTTP method is POST.
To demonstrate this, we start by creating a JavaScript function that contains an HTTP request:
JavaScript function
function |
The code above will:
fname
set to “Mary”Now, let’s examine the function that will be executed when the request is done:
|
The function will try to write the response from the operation into an HTML element with id="demo"
.
Let’s create an HTML page with such an element, and a button that executes the function.
Including the JavaScript, the page will look like this:
How to send and receive data using an HTTP request:
<html> |
In the PHP file that receives this HTTP request (demo_ajax.php), we simply use the $_POST
variable to retrieve the fname
variable and send it as a response.
PHP file
$name |