Skip to content

JavaScript post data to URL

  • by

Use Ajax’s traditional way to make an asynchronous HTTP request and post data to a URL. Data can be sent using the HTTP POST method and received using the HTTP GET method.

const Http = new XMLHttpRequest();
const url='https://jsonplaceholder.typicode.com/posts';
Http.open("GET", url);
Http.send();

Http.onreadystatechange = (e) => {
  console.log(Http.responseText)
}

JavaScript post data to URL

Simple example code posting data using ajax.

Using an HTTP test server accepting GET/POST requests https://httpbin.org/, you can use something else.

<!DOCTYPE html>
<html>
<body>
  <script>
   function makeRequest (method, url, data) {
    return new Promise(function (resolve, reject) {
      var xhr = new XMLHttpRequest();
      xhr.open(method, url);
      xhr.onload = function () {
        if (this.status >= 200 && this.status < 300) {
          resolve(xhr.response);
        } else {
          reject({
            status: this.status,
            statusText: xhr.statusText
          });
        }
      };
      xhr.onerror = function () {
        reject({
          status: this.status,
          statusText: xhr.statusText
        });
      };
      if(method=="POST" && data){
        xhr.send(data);
      }else{
        xhr.send();
      }
    });
  }

  //POST example
  var data={"person":"john","balance":1.23};
  makeRequest('POST', "https://httpbin.org/param1=yoyoma",data).then(function(data){
    var results=JSON.parse(data);
  });

</script>
</body>
</html>

Output:

JavaScript post data to URL

More examples

let xhr = new XMLHttpRequest();
xhr.open("POST", "https://reqbin.com/echo/post/json");

xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");

xhr.onload = () => console.log(xhr.responseText);

let data = `{
  "Id": 78912,
  "Customer": "Jason Sweet",
}`;

xhr.send(data);

Output: {“success”:”true”}

Do comment if you have any doubts or suggestions on this JS post data topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading