Skip to content

Instantly share code, notes, and snippets.

@tbhaxor
Created November 1, 2019 20:52
Show Gist options
  • Save tbhaxor/9927b6af76b52e278a1ddcaf97819717 to your computer and use it in GitHub Desktop.
Save tbhaxor/9927b6af76b52e278a1ddcaf97819717 to your computer and use it in GitHub Desktop.
Learn about Asynchronous Request in Javascript
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Ajax with XHR\n",
"\n",
"In nutshell, AJAX is a concept of sending asynchronous (non-blocking) network request and then using it when the response is sent\n",
"\n",
"**CLIENT-SERVER ARCHITECTURE** When a client wants some resource from the server, it opens a `GET` request and wait for the server to server to respond. This is also called synchronous requests.\n",
"\n",
"In synchronous requests, the HTTP requests have to wait for the current request to be completed at first. \n",
"\n",
"In asynchronous requests, while one HTTP request is sent, the webpage can do other things like loading other stuff. When the client gets the response from the server, a callback function attached to actual request is fired which contains all the produres to be executed\n",
" \n",
"\n",
"## What is AJAX\n",
"\n",
"+ short for **A**synchronous **J**avascript **A**nd **X**ML\n",
"+ in early 90's, Microsoft Outlook team added the XMLHTTP in Internet Explorer\n",
"+ earlier known as **XMLHttpRequest**\n",
"+ ajax is essentially the technique of using XMLHTTPRequest to fetch data and then modify the current page.\n",
"+ used to call apis\n",
"\n",
"**NOTE** Since the main file format that was originally used for asynchronous data exchange were XML files, its not mandatory to use XML only. You can use JSON - TEXT or anything\n",
"\n",
"### AJAX: Creating XHR object\n",
"```js\n",
"const asyncRequestObject = new XMLHttpRequest();\n",
"```\n",
"\n",
"### AJAX: Opening the request\n",
"\n",
"```js\n",
"asyncRequestObject.open('GET', 'https://unsplash.com', false); // this will not send the request\n",
"```\n",
"\n",
"### AJAX: Sending XHR request\n",
"```\n",
"asyncRequestObject.send();\n",
"```\n",
"\n",
"### AJAX: Handling Success\n",
"```js\n",
"function handleSuccess () {\n",
" // in the function, the `this` value is the XHR object\n",
" // this.responseText holds the response from the server\n",
" console.log( this.responseText ); // the HTML of https://unsplash.com/\n",
"}\n",
"\n",
"asyncRequestObject.onload = handleSuccess;\n",
"```\n",
"\n",
"### AJAX: Handling Errors\n",
"```js\n",
"function handleError () {\n",
" // in the function, the `this` value is the XHR object\n",
" console.log( 'An error occurred 😞' );\n",
"}\n",
"\n",
"asyncRequestObject.onerror = handleError;\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# AJAX with JQuery\n",
"\n",
"## What is JQuery\n",
"+ incredibly popular JavaScript library\n",
"+ provides a lot of functionality right out of the box\n",
"+ getting jQuery $\\to$ https://code.jquery.com/\n",
"\n",
"## Using AJAX\n",
"\n",
"+ [`$.ajax()`](http://api.jquery.com/jQuery.ajax/) is the function for sending and handling ajax request\n",
"\n",
"\n",
"### JQuery: Defining AJAX\n",
"```js\n",
"$.ajax(\"URL TO FETCH\", {CONFIG OBJECT});\n",
"\n",
"// or \n",
"\n",
"$.ajax({CONFIG OBJECT});\n",
"```\n",
"\n",
"### JQuery: Making AJAX Call\n",
"```js\n",
"$.ajax({\n",
" url: 'https://swapi.co/api/people/1/'\n",
"});\n",
"```\n",
"\n",
"### JQuery: Handling Success\n",
"```js\n",
"function handleResponse(data) {\n",
" console.log('the ajax request has finished!');\n",
" console.log(data);\n",
"}\n",
"\n",
"$.ajax({\n",
" url: 'the http url'\n",
"})\n",
" .done(handleResponse); // handle request like onload in XHR\n",
"```\n",
"\n",
"## Other Asynchronous Method\n",
"\n",
"+ [`.get()`](http://api.jquery.com/jQuery.get/)\n",
"+ [`.getJSON()`](http://api.jquery.com/jQuery.getJSON/)\n",
"+ [`.getScript()`](http://api.jquery.com/jQuery.getScript/)\n",
"+ [`.post()`](http://api.jquery.com/jQuery.post/)\n",
"+ [`.load()`](http://api.jquery.com/jQuery.load/)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# AJAX with Fetch\n",
"\n",
"## What is Fetch\n",
"+ new way to make network requests\n",
"+ promise based\n",
"+ need polyfill, if not supported by the browser\n",
"\n",
"### Fetch: Sending Requests\n",
"```js\n",
"fetch('URL', {}); // the {} is the options to be sent with request\n",
"```\n",
"\n",
"### JQuery: Handling Requests\n",
"```js\n",
"fetch(\"URL\")\n",
" .then(function(response) {\n",
" console.log(response.status); // showing the status code of HTTP response\n",
" });\n",
"```\n",
"\n",
"### JQuery: Getting the Data\n",
"```js\n",
"fetch(\"URL\")\n",
" .then(response => response.text()) // the body will be extracted\n",
" .then(console.log); // the body will be logged on the console\n",
"```\n",
"\n",
"### JQuery: Handling Error\n",
"```js\n",
"fetch(\"URL\")\n",
" .then(response => response.text())\n",
" .then(console.log)\n",
" .catch(console.error); // error will be logged while parsing/send/recieving\n",
"```"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "jp-Babel (Node.js)",
"language": "babel",
"name": "babel"
},
"language_info": {
"file_extension": ".js",
"mimetype": "application/javascript",
"name": "javascript",
"version": "12.13.0"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment