Post with XMLHttpRequest

·

3 min read

Hi everyone, in this blog I want to go over a simple post request using node XMLHttpRequest. XMLHttpRequest is an javascript object api that allows browsers and servers to transfer data. What we going to do is to post data into dummy server. The tools we are going to use is VSCode with one plugin called Live Server.

Let's start with creating a file name index.html and add boiler plate template.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>XMLHttpRequest</title>
</head>
<body>


</body>
</html>

Next lets add a form and connect our javascript file. In the form we are going to have input with type of button and inline function called submitForm.

...
<body>
<h1>Post with XMLHttpRequest</h1>
    <form>
        <input type="text" id="title">
        <input type="text" id="body">
        <input type="button" value="Submit" onclick="submitForm()" />
    </form>

<script src="script.js"></script>
</body>
...

Now its a good time to use our live server plugin. Left click on the index.html and click on open with live server. The browser should look this:

firstPage.PNG

Now the fun begins with javascript. Create a file name scritp.js. XMLHttpRequest is window object meaning that it is only available in the browser. Let's initialize XMLHttpRequest and call it xhr. Also we are going to get the id elements from html.

const xhr = new XMLHttpRequest();

const body = document.getElementById('body');
const title = document.getElementById('title');

Next lets create the function submitForm(). In this function we going to post request with a dummy server from JSONplaceholder. Within the json placeholder we can see what the server payload looks like.

{
  id: 1,
  title: '...',
  body: '...'
}

As you can see our only inputs title and body. We are going to get the data from the user therefore are going convert it to a string.

  let json = JSON.stringify({
    title: title.value,
    body: body.value
    });

With XMLHttpRequest we going to use the open method for a request. This method takes in five parameters. For more information about open method XMLHttpRequest.open().

open(method, url)
open(method, url, async)
open(method, url, async, user)
open(method, url, async, user, password)

In this method we are going to use "POST" method and our url is "jsonplaceholder.typicode.com/posts". Next lets tell the server what type of data it is and its value. It is called the header for more information XMLHttpRequest.setRequestHeader().

setRequestHeader(header, value)

Lastly lets send our data to the server. The send method accepts one parameter. For more information send.

send()
send(body)

The final javascirpt code should look like this:

const xhr = new XMLHttpRequest();

const body = document.getElementById('body');
const title = document.getElementById('title');

function submitForm() {

  let json = JSON.stringify({
    title: title.value,
    body: body.value
    });
  xhr.open("POST", 'https://jsonplaceholder.typicode.com/posts/')
  xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8')

  xhr.send(json);
}

Now we can test our code. Fill in the input like so..

secondPage.PNG

I'm using chrome for my web browser. Left click on the page and click on inspect then click on network tap.

thridPage.PNG.

Now its time send over our data.

headers.PNG

If you click on the post you can see that the status code is 201 meaning it was received. Then if you click on response it shows you what the server expected from the user.

response.PNG

This was a short intro using XMLHttpRequest for a post request. Any comments or your thoughts please leave it below.

Source:

Github Repo

XMLHttpRequest

MDN