create an ajax request post in javascript

You can create an Ajax POST request in JavaScript using the XMLHttpRequest (XHR) object. Here is an example code snippet:

index.tsx
const xhr = new XMLHttpRequest();
const url = 'http://example.com/api/';
const data = JSON.stringify({username: 'testuser', password: 'testpassword'});

xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    const response = JSON.parse(xhr.responseText);
    console.log(response);
  }
};
xhr.send(data);
431 chars
14 lines

In this example, we create a new XHR object and specify the URL and data payload for the POST request. We then set the request header to 'Content-Type: application/json' to indicate that we are sending JSON data in the request body. We also define an anonymous callback function to handle the response when the request completes.

Finally, we send the request using the send() method, passing in the data payload as an argument.

gistlibby LogSnag