Send Post Data Using Xmlhttprequest

Send POST data using XMLHttpRequest

When working with JavaScript, there may be times when you need to send data to a server using the HTTP POST method. One way to achieve this is by using the XMLHttpRequest object, which allows you to make HTTP requests from the browser.

In this article, we will explore how to send POST data using the XMLHttpRequest object in JavaScript. We will discuss two different approaches to accomplish this task.

Approach 1: Using the setRequestHeader() method

The first approach involves using the setRequestHeader() method to set the appropriate headers for the POST request. Here’s an example:

const xhr = new XMLHttpRequest();
const url = 'https://example.com/api';
const data = JSON.stringify({ name: 'John', age: 30 });

xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/json');

xhr.onreadystatechange = function() {
  if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
    console.log(xhr.responseText);
  }
};

xhr.send(data);

In the above code snippet, we create a new instance of the XMLHttpRequest object and specify the URL and data for the POST request. We then set the request header using the setRequestHeader() method, specifying the content type as JSON. Finally, we send the data using the send() method.

Approach 2: Using the FormData object

The second approach involves using the FormData object to easily construct and send form data. This approach is particularly useful when dealing with HTML forms. Here’s an example:

const xhr = new XMLHttpRequest();
const url = 'https://example.com/api';
const formData = new FormData();

formData.append('name', 'John');
formData.append('age', '30');

xhr.open('POST', url, true);

xhr.onreadystatechange = function() {
  if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
    console.log(xhr.responseText);
  }
};

xhr.send(formData);

In the above code snippet, we create a new instance of the XMLHttpRequest object and specify the URL. We then create a new FormData object and append the form data to it using the append() method. Finally, we send the form data using the send() method.

Both approaches allow you to send POST data using the XMLHttpRequest object in JavaScript. Choose the one that best suits your needs and requirements.

That’s it! You now know how to send POST data using the XMLHttpRequest object in JavaScript. Happy coding!


Posted

in

, ,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *