Thomas Reggi's Profile Image

@thomasreggi 🌸

Ajax POST v.s. Form POST

December 16, 2020 (Syndicated From

There are some concrete details I would love to dive into when it comes to the main differences between using a native html form and using ajax to send data to a server.

The main objective of both a html form and an ajax post is to move data, but there also may be additional goals and needs. One notable one is navigation / redirection, most of the time when a user submits data through a action or event we want to move the user to a different page.

When a form is submit without any manipulation from JavaScript the user is sent to a completely different url and the data is sent along as well ether as get params or as a body.

The one benefit of doing this is that a user actually will be redirected to that domain for a brief moment, and in this jump it can set cookies for a user along the way.

Let’s say you have two different endpoints on an API. Both use the POST method. One returns JSON, the other returns with a redirect.

When you post data with an ajax request it does not change the navigation or url of the user. So if I hit both urls described above nothing will happen to the users navigation.

Of course with JavaScript you can perform a redirect by changing the window location. However, this will act as a get request. There is no way for the server to post via the browser.

Both forms and ajax solutions are very similar. The only difference is when using a third party API that redirects the user for you. If you need to use a post request to send data and the location will reroute the user, you will need to use a form post and not an ajax.