We're getting into some AJAX questions today.
As a result, your application works much faster and is more responsive to user actions.
*We use XMLHttpRequest (XHR) objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in AJAX programming.
Here's a quick diagram and explanation from w3schools of how it works:
- An event occurs in a web page (the page is loaded, a button is clicked)
- The XMLHttpRequest object sends a request to a web server
- The server processes the request
- The server sends a response back to the web page
I'm going to take straight from Yangshun on this one as I think they hit the points well:
- Better interactivity. New content from the server can be changed dynamically without the need to reload the entire page.
- Reduce connections to the server since scripts and stylesheets only have to be requested once.
- See advantages of an SPA.
- Dynamic webpages are harder to bookmark.
- See disadvantages of an SPA.
JSONP can be seen as a workaround to the cross-origin domain policy and doesn't use the XMLHttpRequest object. JSONP stands for JSON with Padding. JSONP won't use the XMLHttpRequest object. Instead, it uses
<script> tags. This eliminates the issues caused by the cross-origin domain policy. Requesting an external script from another domain doesn't create this problem, hence JSONP.
JSONP works by making a request to a cross-origin domain via a
<script> tag and usually with a callback query parameter, for example:
https://example.com?callback=printData. The server will then wrap the data within a function called
printData and return it to the client.
An aside: JSONP can be unsafe and has some security implications, so you need to trust the provider of the JSONP data. CORS is the modern recommended approach.
That's all for today, please leave any comments/questions/corrections in the comments. Thanks!
And an additional thank you to Flatiron alum: Marissa O. who is a badass developer at Forbes magazine for directing me to his blog!