Home >Web Front-end >JS Tutorial >How to Send POST Data with XMLHttpRequest?

How to Send POST Data with XMLHttpRequest?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-02 14:27:38381browse

How to Send POST Data with XMLHttpRequest?

How to Submit POST Data using XMLHttpRequest

In scenarios where an application needs to submit data to the server, one can utilize XMLHttpRequest to send POST data.

In the provided HTML code, data is encapsulated within hidden form fields. To mirror this behavior using XMLHttpRequest in JavaScript, follow these steps:

  1. Create an XMLHttpRequest object:

    var http = new XMLHttpRequest();
  2. Set the request method and URL:

    var url = 'get_data.php';
    http.open('POST', url, true);
  3. Set the request headers:

    http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  4. Define the event listener for ready state changes:

    http.onreadystatechange = function() {//Call a function when the state changes.
     if(http.readyState == 4 && http.status == 200) {
         alert(http.responseText);
     }
    }
  5. Send the data:

    http.send(params);

For cases where the data is stored in an object, transform it into a URL-encoded format using the provided code snippet.

The above is the detailed content of How to Send POST Data with XMLHttpRequest?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn