What is the difference between POSTing with an HTML Form element and with an XMLHTTPRequest?
Why can a form allow a redirect to another web page, but apparently a XMLHTTPRequest cannot?
If I'm making POST requests, I should be able to formulate a request with the same attributes and expect the same behavior.
What is the difference between POSTing with an HTML Form element and with an XMLHTTPRequest?
An XMLHttpRequest allows for asynchronous operations to be performed, which don't block the UI of the client. When using an HTML form, the client is blocked while the operation is being performed.
Also (as you point out), an HTML form submission causes a page reload to a specified URL, whereas an XHR does not - - it simply results in data being returned. The returned data may only be a portion of a page's content, so XHR does not cause a full page reload. It allows us to dynamically update a portion of a page.
Why can a form allow a redirect to another web page, but apparently a XMLHTTPRequest cannot?
An XHR can have a "success" callback function configured for it. When the operation is successfully completed, the callback function can do whatever you like, including a redirect.
If I'm making POST requests, I should be able to formulate a request with the same attributes and expect the same behavior.
Do you mean that an HTML request should be able to be configured the same as an XHR request? If so, then no, that's not the case. An XHR request can be configured to a very granular level (user name and password, data type, caching, success callback, failure callback, etc.). This (and the asynchronous nature of XHR) is the reason that XHR is popular.
I think you should walk through a brief history and evolution.
Back in old days when HTML HTTP was simple people used to post forms but it had some issues ?
Ok but what if user did not entered correct form values ??? Net use to be slow back then so came in hero JavaScript
Now smart people came with XMLHTTPRequest/AJAX why to refresh page why ?
With better browsers and server this evolved in SPA (Single Page Application) and much more.
Import one is With some code,
even XHR can redirect to other pages or reload page ex window.location = '' And also FORM can be prevented from redirecting ex e.preventDefault()
Check AJAX related information it would help you understand the why part and why its so much fun.
Hope that helped
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With