Gabriele Ferro Home

How to handle the response after a POST request

Day 50: 24 September 2020

A few days ago I wrote a code that allowed the data to be sent to the backend via a POST request.

In short, the user selects products to add to his basket and then confirms the request by filling in a form with his personal data.

When the user clicks on the button to confirm the order, they are sent via a POST request:

  • an array containing the IDs of the products in the basket;
  • a contact object containing the information extracted from the form.

I had already made a GET request to retrieve information from the backend, but I still hadn't figured out how to manage the response given by the server after a POST request.

So, I had to document myself, and a review of the courses was necessary.

Unfortunately, among the resources and courses I used for the review, I could not find the information I was looking for.

Google to the rescue!

Following the standards, gave me the answers I was looking for, and although I still use XMLHttpRequest instead of fetch(), this is the solution I was looking for.

I also found "The Best Examples of jQuery" but I decided that I will only use it as a last resort, because even though I can use it for the project, I'm not a fan. At the moment, only 1 line of code uses jQuery.

**Today’s Progress:**

First of all to avoid the default behavior of the button submit, i.e. page refresh:

Then, once the request is sent, the code will handle the response once loaded, using the onload() method.

Once we receive the response from the backend, we use the alert method to highlight the order ID. We could have shown the entire response but I was only interested in the ID, and it was easier to debug the code.

Then we build a string that will represent the web address to which we redirect our user.

And we make the redirection.


I will ask my mentor if the existence of the action attribute in HTML is still necessary, that is:

<form id="myForm" action="confirmation-commande.html" method="POST">

Now all I have left is:

  1. Write some JavaScript on the confirmation page to retrieve the information from the address bar;
  2. Give some love to the site in the form of CSS;
  3. Choose some text content and some images to fill the various pages;
  4. Transform XMLHttpRequest into fetch() in order to use the promises;
  5. Write a test plan;
  6. Put some comment on the code... Yes, I know.

**Link to tweet:**

[twitter-follow screen_name='20Gabriele20']

June 2024


Gabriele Ferro Home
Copyright © Ferro Gabriele. All rights reserved.