Learn Dynamic HTML With JS
Lesson 1 - HTML JS Relationship
Lesson 2 - HTML DOM
Lesson 3 - Browser BOM
Lesson 4 - Basic Interaction
Lesson 5 - Manipulating CSS
Lesson 7 - Form Handling
POST requests are typically considered more robust and secure compared to GET requests. They are primarily used to send data from the client (such as user input from forms) to the server. Unlike GET requests, POST requests do not expose parameters in the URL, which enhances security, especially when handling sensitive information.
Here's an example demonstrating how to create a POST request using XMLHttpRequest()
in JavaScript:
<!DOCTYPE html> <html> <head> <title>POST Request</title> </head> <body> <p id="responseMessage"></p> <script> const xhttp = new XMLHttpRequest(); xhttp.onload = function() { document.getElementById("responseMessage").innerHTML = this.responseText; }; // Define the JSON data to be sent const postData = JSON.stringify({ title: "test" }); xhttp.open("POST", "https://jsonplaceholder.typicode.com/posts"); xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); // Set appropriate request header xhttp.send(postData); // Send the POST request with the JSON data </script> </body> </html>
Explanation:
XMLHttpRequest()
named xhttp
.onload
function that executes when the POST request completes. It will update the responseMessage
element to add the response received from the request.xhttp.open()
to specify the HTTP method (POST) and the URL (https://jsonplaceholder.typicode.com/posts
) where the data will be sent.xhttp.send()
to send the POST request, passing data (JSON.stringify({ title: 'test' })
in this example).This example demonstrates how to send data to a server using a POST request. Adjust the data and URL according to your specific use case.