Xu Wang
Xu Wang

Reputation: 344

What is the difference between ajax post request and form post request?

on server side, for example, I use flask to handle these post requests, the same code can handle the two type requests, but on client side, ajax request will not let the browser to refresh the whole page, but the form does. So what is the difference in deep, is some header field not same?? or something else?? Thanks!

Upvotes: 6

Views: 2699

Answers (4)

Quentin
Quentin

Reputation: 944157

Submitting an HTML form constructs an HTTP request formatted according to the rules defined for HTML forms and causes the browser to navigate to the response it gets.

Making a request with JavaScript allows the programmer to construct a much wider variety of requests — including adding custom headers, formatting data in different ways (such as JSON), and identically to how an HTML form would construct the request — and causes the response to be processed with JavaScript.

In general, when writing server-side code, you shouldn't need to care if the request came from JavaScript or an HTML form. There are situations where you do, but usually only as an XY Problem.

For example, you might wish to respond to a regular form submission with an HTML document (because the browser is navigating to it) but to an Ajax request with JSON (because you want to process it easily). In this case the JavaScript should set an Accept request header to tell the server that it would prefer a JSON response. Then the server-side code you write should look at that to determine if HTML or JSON is preferred (and not worry why HTML or JSON is preferred).

Upvotes: 2

Dean Petty
Dean Petty

Reputation: 3

Form and Ajax requests send to the back in the same way. For Flask, you capture the POST request and it would be identical if the Ajax contained all the same information from the form.

What submits the form (And causes the fresh of the page) is a "onsubmit" event the form fires to the DOM. This can actually be overridden if you desire. This is often done with the "PreventDefault" function. This i believe has been covered several times on the site. You may have just been missing the concept of the "onsubmit" event from the form.

Upvotes: 0

kirupakaranh
kirupakaranh

Reputation: 239

Ajax request is an xhr request sent in the background asynchronously and handled by your javascript code whereas form request is a normal request and browser page will be reloaded as well as the response rendered by the browser

Upvotes: 0

dangee1705
dangee1705

Reputation: 3520

There is no difference, only that AJAX is, as the acronym suggests, asynchronous, which means it does not block anything else from running. Both the form and an AJAX request send a POST request the only difference is that the browser uses the response from the forms POST request to load the new page where as the AJAX requests response is passed to a callback in JavaScript.

Upvotes: 7

Related Questions