What role does the Fetch API play in sending data from JavaScript to a PHP server in a web application?
The Fetch API is used in JavaScript to make asynchronous HTTP requests to a server, including sending data to a PHP server in a web application. This API allows for easy sending of data in various formats such as JSON or FormData to the server, where PHP scripts can then process the data and respond accordingly.
<?php
// Receive data sent from JavaScript using the Fetch API
$data = json_decode(file_get_contents("php://input"));
// Process the data as needed
// For example, if the data sent is a JSON object with a 'name' key
if(isset($data->name)){
$name = $data->name;
// Perform actions with the received data
echo "Hello, " . $name . "!";
} else {
echo "No data received.";
}
?>
Related questions
-
mail function PHP multiple recipients
-
count() function PHP
-
htmlspecialchars htmlentities UTF-8 encoding