{"id":21696333,"url":"https://github.com/dinanathsj29/ajax-asynchronous-javascript-and-xml-course-tutorial","last_synced_at":"2025-10-10T14:33:51.414Z","repository":{"id":121989956,"uuid":"208965402","full_name":"dinanathsj29/ajax-asynchronous-javascript-and-xml-course-tutorial","owner":"dinanathsj29","description":"Learn and understand how to work with AJAX methodology/concepts to fetch/exchange (send and receive data) to-from web server","archived":false,"fork":false,"pushed_at":"2019-09-25T17:36:35.000Z","size":686,"stargazers_count":9,"open_issues_count":0,"forks_count":3,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-12T12:08:53.545Z","etag":null,"topics":["ajax","ajax-upload","fetch-api","json","json-parse","xmlhttprequest"],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dinanathsj29.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-09-17T05:20:28.000Z","updated_at":"2024-02-10T17:55:56.000Z","dependencies_parsed_at":null,"dependency_job_id":"569a0478-4cbe-42d1-8ed4-73df0115e056","html_url":"https://github.com/dinanathsj29/ajax-asynchronous-javascript-and-xml-course-tutorial","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/dinanathsj29/ajax-asynchronous-javascript-and-xml-course-tutorial","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dinanathsj29%2Fajax-asynchronous-javascript-and-xml-course-tutorial","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dinanathsj29%2Fajax-asynchronous-javascript-and-xml-course-tutorial/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dinanathsj29%2Fajax-asynchronous-javascript-and-xml-course-tutorial/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dinanathsj29%2Fajax-asynchronous-javascript-and-xml-course-tutorial/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dinanathsj29","download_url":"https://codeload.github.com/dinanathsj29/ajax-asynchronous-javascript-and-xml-course-tutorial/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dinanathsj29%2Fajax-asynchronous-javascript-and-xml-course-tutorial/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":279004174,"owners_count":26083688,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-10T02:00:06.843Z","response_time":62,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ajax","ajax-upload","fetch-api","json","json-parse","xmlhttprequest"],"created_at":"2024-11-25T19:19:29.906Z","updated_at":"2025-10-10T14:33:51.385Z","avatar_url":"https://github.com/dinanathsj29.png","language":"JavaScript","readme":"\u003cp align=\"center\"\u003e\n \u003cimg src=\"_images-ajax/ajax-logo-1.png\" alt=\"AJAX - Asynchronous JavaScript and XML\" title=\"AJAX - Asynchronous JavaScript and XML\" width=\"200\" /\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n \u003cimg src=\"_images-ajax/ajax-logo-2.png\" alt=\"AJAX - Asynchronous JavaScript and XML\" title=\"AJAX - Asynchronous JavaScript and XML\" /\u003e\n\u003c/p\u003e\n\nAJAX Asynchronous JavaScript and XML\n=====================\n\nWelcome\n---------------------\n\nAbout the Course/Tutorial\n---------------------\nHi All, I'm **`Dinanath Jayaswal, Senior UI/Web Developer and Adobe Certified Expert Professional`**, I wanna welcome you to `AJAX (Asynchronous JavaScript and XML) Crash Course for Beginners`. This course/tutorial will give you a complete understanding of how to work with AJAX methodology/concepts to fetch/exchange (send and receive data) to-from web server.\n\nThis course will cover the basics of understanding JSON and AJAX using the practical implementation in your web development project. In this tutorial will explore how AJAX works and how it is used in web applications, will also see what `Fetch` and `XHR` are and how they work to get data.\n\n\nWho is this for? \n---------------------\nThis course is for anyone interested in quickly learning AJAX+JSON \u0026 it's power to utilize it in Web Development. \n\nThis Course/Tutorial is ideal for:\n- Anyone who wants to learn AJAX from scratch\n- Programmers and Developers at any level\n- Web developers / Web Designers / Application developers / Software Developers\n- Mobile Developers using the HTML5 Stack\n- Anyone who wants to interchange data exchange between clients and servers\n- Anyone who wants to create Dynamic Applications and use data seamlessly within web applications\n\nThis course/Tutorial is for anyone and everyone, Almost everyone!\n\nWhy learn AJAX\n---------------------\n`AJAX stands for Asynchronous JavaScript and XML`. JSON and AJAX together provide web developers with incredible opportunities to `integrate external data seamlessly (without page refresh/reload)` into web applications. AJAX helps to create and develop an amazing `interactive dynamic applications with better user experiences` that can synchronize data between your database and your front end HTML code (`minimizes the load on your server` and makes your `applications respond quickly and without reloading the HTML` page).\n\n\nCourse/Tutorial achievement\n---------------------\n\nCourse/Tutorial Goal\n---------------------\nAfter completing/attending this AJAX Course/Tutorial, participants should be able to: \n- Understand what and why AJAX and JSON\n- Use AJAX to fetch/exchange data in web projects\n- Exchange Data with JSON format and use JSON in Web development/project\n\nPrerequisites for current course / What you need to know\n---------------------\n- Basic knowledge and understandings of HTML, CSS, JavaScript, jQuery and ASP/PHP\n- Knowledge of using any text editor and a web browser\n- Basics of Browser and Internet\n- A basic understanding of Client Side vs Server Side\n- Working knowledge of JSON will be an added advantage\n\nBefore starting with AJAX it is advisable to view and go through the following course/tutorials to get knowledge of: \n- **Web Design Development Technology Fundamentals** - [Web Design Development Technology Fundamentals\n](https://github.com/dinanathsj29/web-design-development-fundamentals-tutorial),\n  - **HTML5** - [HTML5 Essentials Tutorial](https://github.com/dinanathsj29/html5-essentials-tutorial),\n    - CSS3 - [CSS3 Fundamentals Tutorial](https://github.com/dinanathsj29/css3-fundamentals-tutorial),\n      - **JavaScript** [JavaScript tutorial for Beginners](https://github.com/dinanathsj29/javascript-beginners-tutorial),\n        - **JSON** [JSON JavaScript Object Notation crash course](https://github.com/dinanathsj29/json-javascript-object-notation-crash-course)\n\nTopics included/covered\n=====================\n\n1. [Introduction to AJAX](#1-introduction-to-ajax)\n  - 1.1. [What is AJAX?](#11-what-is-ajax)\n  - 1.2. [Why use AJAX?](#12-why-use-ajax)\n  - 1.3. [Synchronous vs Asynchronous](#13-synchronous-vs-asynchronous)\n  - 1.4. [AJAX History](#14-ajax-history)\n  - 1.5. [AJAX Technologies](#15-ajax-technologies)\n  - 1.6. [How AJAX works?](#16-how-ajax-works)\n  - 1.7. [AJAX Browser support](#17-ajax-browser-support)\n  - 1.8. [Where AJAX is used? AJAX examples](#18-where-ajax-is-used-ajax-examples)\n  - 1.9. [Drawbacks-Disadvantages of AJAX](#19-drawbacks-of-ajax)\n \n2. [AJAX XMLHttpRequest](#2-ajax-xmlhttprequest)\n  - 2.1. [What is XMLHttpRequest? (XHR)](#21-what-is-xmlhttprequest)\n  - 2.2. [Libraries and other Methods](#22-libraries-and-other-methods)\n  - 2.3. [XMLHttpRequest-loading JSON data](#23-xmlhttprequest-loading-json-data)\n  - 2.4. [XMLHttpRequest-loading web API data](#24-xmlhttprequest-loading-web-api-data)\n  - 2.5. [GET vs POST method](#25-get-vs-post-method)\n  - 2.6. [XMLHttpRequest-onreadystatechange](#26-xmlhttprequest-onreadystatechange)\n\n3. [AJAX Live Demo Example](#3-ajax-live-demo-example)\n  - 3.1. [XMLHttpRequest-Get Post Data-Basic](#31-xmlhttprequest-get-post-data-basic)\n  - 3.2. [XMLHttpRequest-Get Post Data-Advanced](#32-xmlhttprequest-get-post-data-advanced)\n\n4. [JavaScript Http Request with fetch() API and Promises](#4-javascript-http-request-with-fetch()-api-and-promises)\n  - 4.1. [Introduction to fetch() API](#41-introduction-to-fetch()-api)\n  - 4.2. [fetch() API demo example](#42-fetch()-api-demo-example)\n\n5. [JavaScript Http Request with Axios library](#5-javascript-http-request-with-axios-library) \n\n  - 5.1. [Introduction to fetch() API](#51-introduction-to-axios)\n  - 5.2. [Axios demo example](#52-axios-demo-example)\n\n6. [AJAX Reference and Resources](#6-ajax-reference-and-resources)\n\n1 Introduction to AJAX\n=====================\n\n1.1. What is AJAX?\n--------------------- \n\n- `AJAX (Asynchronous JavaScript and XML)`\n- `AJAJ (Asynchronous JavaScript and JSON)`\n\nThe process of **`sending and receiving data on the fly without page refresh/reload`** is known as AJAX\n\n- AJAX stands for Asynchronous JavaScript and XML enable web applications to retrieve data from the server asynchronously\n- AJAX is *not a new programming language* - actually its a methodology or concepts or special way to bring JavaScript and XML (now a days JSON) together to produce impressive results\n- **AJAX is set of web technologies** - just uses a combination of:\n - A browser built-in `XMLHttpRequest object` to request data from a web server\n - `JavaScript and HTML DOM` to display or use the data\n - It is a group of inter-related technologies like **`JavaScript, DOM, XML/JSON, HTML/XHTML, CSS, XMLHttpRequest`** etc.\n- AJAX allows the web page to `\"talk/communicate\"` with the server behind the scene (send and receive data asynchronously)\n- AJAX sends, receives and process information to or from the server without page refresh/reload (does not interfere with current web page/data) \n- Web application using AJAX enables partial page updates, ie. only the related section of the page is updated, without reloading the entire page\n- AJAX minimize the page refreshes, so web sites/pages/web apps show more fluid/elegant-better experience to users\n- AJAX and JSON together provide the ability to JavaScript code to make HTTP requests to get data and update page content with new data\n- Now a days **`JSON`** has replaced `XML` for the most part and almost all dynamic websites use/implements AJAX concepts and methodology\n\n\n1.2. Why use AJAX?\n--------------------- \n\n- **`AJAX is pretty fast`** - as it allows you to send and receive data asynchronously without reloading the web page\n- **`AJAX applications are non-blocking`** - as AJAX requests are asynchronous, we don't have to wait for the request processing to complete\n- **`AJAX allows web pages to be updated asynchronously`** by exchanging data with a web server behind the scenes, this simply means that it is possible to update parts of a web page, without reloading the whole page\n- **`Better performance and reduced network traffic`** - AJAX helps to send and receive only the required data so better performance\n- **`No refresh-reload/No screen flicker`** - only a portion of the page is updated avoiding full page refresh/reload and screen flickering\n- AJAX is used for building web-based interactive applications that process user requests immediately - **`no page reload`** to bring data into your application\n- AJAX allows us to send and fetch only important/valuable part of data/information to/from the server, not the entire page so it **`makes your application interactive and faster`**\n- XML is commonly used as the format for receiving server data, although **`any data exchange/interchange format can be used`** including JSON, plain text\n- AJAX is a web browser technology **`independent of web server software/platform`**\n- **`Data-driven`** as opposed to Page-driven methodology\n- AJAX is the most viable, popular **`Rich Internet Application (RIA) technology`** so far with tremendous industry momentum and several tool kit and frameworks are emerging\n\n1.3. Synchronous vs Asynchronous\n---------------------\n1.3. Understanding Synchronous vs Asynchronous\n---------------------\n\n### 1.3.1. Synchronous (Classic Web-Application Model)\nA synchronous request **`blocks the client until the operation completes`** i.e. browser is unresponsive. In such a case, the JavaScript engine of the browser is blocked.\n\n\u003e **Example**:\n - **Mail application** - New email arrived - whole page refresh to show latest inbox and email\n - **Chat application** - On new message arrival complete chat application reloads\n - **Travel Website** - Destination place selected - request went to server -\u003e got response -\u003e page refresh to show fare details\n\n### 1.3.2. Asynchronous (AJAX Web-Application Model)\n\nAn asynchronous request **`doesn’t block the client`** i.e. browser is responsive. At that time, the user can perform another operation also. In such a case, the JavaScript engine of the browser is not blocked.\n\n\u003e **Example**:\n- While working with AJAX-based **Rich Internet Application (RIA)** we can work with a specific part of an application - send/receive data, so application is interactive and faster\n\n| Synchronous execution | Asynchronous execution |\n| ---------------------------------------------- | ---------------------------------------------- |\n| When you execute something synchronously, you wait for it to finish before moving on to another task (QUEQE)| When you execute something asynchronously, you can move on to another task before it finishes (NO QUEQE) |\n| Synchronous, or Synchronized means \"connected\", or \"dependent\" in some way | Asynchronous means they are totally independent and neither one must consider the other in any way, either in the initiation or in execution |\n| Synchronize task are coordinated or combined with each other - one finishes than only another or next starts | Asynchronous task is not co-coordinated with other tasks (can execute in any order)|\n| In the synchronous case, each statement completes before the next statement is run. In this case the program is evaluated exactly in order of the statements \u003cbr/\u003eBe execute in order: 1 --\u003e 2 --\u003e 3 | In Asynchronous case, you don't stop execution, you can continue executing other code while the 'request' is being made \u003cbr/\u003e1 or 2 or 3 anybody can execute and finish any time|\n| **Example:** You are in a queue to get a **`food coupon or movie ticket`**. You cannot get one until the front of you gets one, and the same applies to the people queued behind you | **Example:** **`You are in a restaurant`** with many other people. You and Other people(everybody) can also order their food at the same time, no one has to wait for food to be cooked and served to you before they can order |\n| **Example:** A `relay race` - \u003cbr/\u003e `1st runner` runs till given distance, stops and passes the baton to the `2nd runner` and process continues till last runner | **Example:** `100 meters race or Marathon race` - any runner can run randomly and win | \n\n\n\n1.4. AJAX History\n--------------------- \n\n1.4. History of AJAX\n--------------------- \n\n| Year | Achievements |\n| ---------------------------------------------- | ---------------------------------------------- |\n| Mid 1990s \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; | Most Web sites were based on static HTML pages, each user action/interaction required a complete new page be loaded from the serve |\n| 1996 | **`iframe tag`** was introduced by **`Internet Explorer`**; like the object element, it can load or fetch content asynchronously |\n| 1998 | **`Microsoft Outlook Web Access team`** developed the concept behind the **`XMLHttpRequest`** scripting object |\n| 1999 | **`XMLHttpRequest (XMLHTTP)`** shipped with **`Internet Explorer 5.0`** |\n| By year 2002 | The functionality of the XMLHTTP ActiveX control in IE 5 was later implemented by **`Mozilla, Safari, Opera, Internet Explorer 7`** and other browsers as the XMLHttpRequest JavaScript object |\n| 2004 | **`Google Gmail`**. Google made a wide deployment of standards-compliant, cross browser Ajax with Gmail |\n| 2004 | October 2004 **`Kayak.com's`** public beta release was among the first large-scale e-commerce |\n| 2005 | **AJAX term coined in 2005 by Jesse James Garrett!** The term Ajax was publicly used on **`18 February 2005 by Jesse James Garrett`** in an article titled **`Ajax: A New Approach to Web Applications`**, based on techniques used on Google pages |\n| 2005 | Google Maps |\n| 2006 | On 5 April 2006, the **`World Wide Web Consortium (W3C)`** released the first draft specification for the XMLHttpRequest object |\n| 2016 | On 6 October 2016, the latest draft of the XMLHttpRequest object was published |\n\n- AJAX concepts are first implemented in the year 2004, a term coined publicly on **`18 February 2005 by Jesse James Garrett`** in an article titled **`Ajax: A New Approach to Web Applications`**\n\n\n1.5. AJAX Technologies\n--------------------- \n\n1.5. Technologies in AJAX\n--------------------- \n\nThe term **`AJAX`** has come to represent a broad group/set of Web Technologies that can be used to implement a Web application that/which communicates with a server in the background (behind the scenes), without interfering with the current state of the page. \n\nAs describe earlier AJAX cannot work independently. AJAX is not a technology but group/set of inter-related technologies used in combination to create interactive webpages.\n\nIn the article titled **`Ajax: A New Approach to Web Applications`** by **`Jesse James Garrett`** that coined the term AJAX, explained that the following technologies are incorporated:\n\n- HTML/XHTML and CSS *(for presentation)*\n- The Document Object Model (DOM) *(for a dynamic display of and interaction with data)*\n- XML or JSON *(for the interchange of data, and XSLT for its manipulation)*\n- The XMLHttpRequest object *(for asynchronous communication)*\n- JavaScript *(to bring these technologies together)*\n\n### 1.5.1. HTML/XHTML and CSS\n - These technologies are used for displaying content (Text/Data - Text Layout Model) and style (Design/Presentation - Box Layout Model) \n - It is mainly used for presentation layer\n\n### 1.5.2. The Document Object Model (DOM)\n - API for accessing and manipulating structured documents\n - It is used for dynamic display and interaction with data\n - Represents the structure of XML and HTML documents\n \n### 1.5.3. XML or JSON\n - Lightweight and popular data exchange/interchange format on the internet today!\n - For carrying data to and from server\n - JSON (Javascript Object Notation) is like XML but short, better, faster, lightweight, popular than XML\n\n### 1.5.4. The XMLHttpRequest object\n - JavaScript object that performs asynchronous interaction with the server\n - For asynchronous communication between client and server\n - **`Sends data from the client in the background -\u003e Receives the data from the server -\u003e Updates the webpage without reloading it`**\n\n### 1.5.5. JavaScript\n - It is used to bring above technologies together (Glue for the whole AJAX operation)\n - Loosely typed scripting language, it is used mainly for client-side logic/validation\n\n1.6. How AJAX works?\n--------------------- \n\nAJAX communicates with the web server using XMLHttpRequest object. Let's try to understand the flow and process of AJAX or how AJAX works (XMLHttp --\u003e Request \u003c-- Response mechanism) as displayed in the image below:\n\n\u003cp\u003e\n \u003cfigure\u003e\n \u0026nbsp;\u0026nbsp;\u0026nbsp; \u003cimg src=\"_images-ajax/1.6.1-how-ajax-works.png\" alt=\"AJAX - How AJAX works - flow diagram\" title=\"AJAX - How AJAX works - flow diagram\" width=\"600\" border=\"2\" /\u003e\n \u003cfigcaption\u003e\u0026nbsp;\u0026nbsp;\u0026nbsp; Image - AJAX - How AJAX works - flow diagram\u003c/figcaption\u003e\n \u003c/figure\u003e\n\u003c/p\u003e\n\n\u003cp\u003e\n \u003cfigure\u003e\n \u0026nbsp;\u0026nbsp;\u0026nbsp; \u003cimg src=\"_images-ajax/1.6.2-how-ajax-works.gif\" alt=\"AJAX - How AJAX works - flow diagram\" title=\"AJAX - How AJAX works - flow diagram\" width=\"600\" border=\"2\" /\u003e\n \u003cfigcaption\u003e\u0026nbsp;\u0026nbsp;\u0026nbsp; Image - AJAX - How AJAX works - flow diagram\u003c/figcaption\u003e\n \u003c/figure\u003e\n\u003c/p\u003e\n\n| Steps - Process | \n| ---------------------------------------------- | \n| 1. **`Client Side`** - An event occurs in a web page (a button is clicked) | \n| 2. An XMLHttpRequest object is created by JavaScript | \n| 3. The XMLHttpRequest object sends a request to a web server | \n| 4. **`Server Side`** - The server processes the XMLHttpRequest request |\n| 5. The server sends a response back to the web page |\n| 6. **`Client Side`** - The response is read by JavaScript |\n| 7. Proper action/activity (like page update and showing the latest data) is performed by JavaScript |\n\n\n1.7. AJAX Browser support\n--------------------- \n\nAll the available browser version cannot support AJAX. AJAX (XMLHttpRequest) is supported well in latest version of all popular browser:\n\n\u003cp\u003e\n \u003cfigure\u003e\n \u0026nbsp;\u0026nbsp;\u0026nbsp; \u003cimg src=\"_images-ajax/1.7.1-ajax-browser-support-2019-sep.png\" alt=\"AJAX Browser support\" title=\"AJAX Browser support\" width=\"1000\" border=\"2\" /\u003e\n \u003cfigcaption\u003e\u0026nbsp;\u0026nbsp;\u0026nbsp; Image - AJAX Browser support - September 2019\u003c/figcaption\u003e\n \u003c/figure\u003e\n\u003c/p\u003e\n\n\u003e **NOTE**:\nBrowser does not support AJAX, simply means that the `browser does not support the creation of Javascript object – XMLHttpRequest object`\n\n\n\n1.8. Where AJAX is used? AJAX examples\n--------------------- \n\nMany famous and widely used web applications use AJAX technology (to Save, Scroll, Autocomplete, AutoSave, etc.), like:\n- Google Gmail, Google Search, Google Maps\n- Facebook \n- Twitter\n- Travel Sites\n- Youtube\n- Online Songs/Video players/websites\n- Chat applications\n\n\n1.9. Drawbacks of AJAX\n--------------------- \n\n1.9. Disadvantages of AJAX\n--------------------- \n\n- Any browser does not support JavaScript or XMLHttpRequest, or has this functionality disabled, will not be able to properly use AJAX-based/dependent pages\n- Some Web applications that use AJAX are built in a way that cannot be read by screen-reading technologies, such as JAWS (In such a case the WAI-ARIA standards provide a way to provide hints)\n- Screen readers may still not be able to properly read the dynamically generated content\n- The asynchronous callback-style of programming required can lead to complex code that is hard to maintain, to debug and to test\n- AJAX requests cannot be bookmarked easily\n\n\n2 AJAX XMLHttpRequest\n=====================\n\n2.1. What is XMLHttpRequest?\n--------------------- \n2.1. What is XMLHttpRequest? (XHR)\n--------------------- \n\n- `XMLHttpRequest` method helps to establish a connection with a specific URL and send or receive data\n- The `XMLHttpRequest` object is the key to AJAX, An object of `XMLHttpRequest` is used for asynchronous communication between client and server\n- The `XMLHttpRequest` object can be used to exchange data with a web server asynchronously (behind the scenes), so it's possible to update parts of a web page, without reloading the whole page\n- `XMLHttpRequest (XHR)` is an API in the form of an object whose methods transfer data between a web browser and a web server in the browser's JavaScript environment\n- `XMLHttpRequest (XHR)` can be used with other protocols than HTTP\n- `XMLHttpRequest (XHR)` works with data other than (JSON, plain text)\n\n### XMLHttpRequest performs following operations:\n\n- `Sends` data from the client in the background\n- `Receives` the data from the server\n- `Updates` the webpage without reloading it\n\n\u003e **XMLHttpRequest Syntax**:\n\n```js \nXMLHttpRequest.open ('http method type', 'url-path');\n\nXMLHttpRequest.open ('GET/POST', '.json file path or web API path');\n```\n\n\n2.2. Libraries and other Methods\n--------------------- \n\nIt's advisable to know plain vanilla JavaScript code to achieve AJAX with XMLHttpRequest.\n\nThere are a bunch of other libraries, methods, and ways to make AJAX calls. Third-party libraries are great, time-saving and make things easier (less code we can write to achieve things):\n\n- jQuery (DOM manipulation library) - $ajax(), $load, $get, $post\n- Angular - HttpClient\n- Axios \n- Superagent\n- Fetch API\n- Prototype\n- Node HTTP\n\n\n2.3. XMLHttpRequest-loading JSON data\n--------------------- \n\n\u003e **Syntax \u0026 Example**: `2.3-loading-json-data/animals1.json`\n\n```json\n[\n {\n \"name\": \"Meowsy1\",\n \"species\": \"cat\",\n \"foods\": {\n \"likes\": [\n \"tuna\",\n \"catnip\"\n ],\n \"dislikes\": [\n \"ham\",\n \"zucchini\"\n ]\n }\n },\n {\n \"name\": \"Barky1\",\n \"species\": \"dog\",\n \"foods\": {\n \"likes\": [\n \"bones\",\n \"carrots\"\n ],\n \"dislikes\": [\n \"tuna\"\n ]\n }\n },\n {\n \"name\": \"Purrpaws1\",\n \"species\": \"cat\",\n \"foods\": {\n \"likes\": [\n \"mice\"\n ],\n \"dislikes\": [\n \"cookies\"\n ]\n }\n }\n]\n```\n\n\u003chr/\u003e\n\n\u003e **Syntax \u0026 Example**: `2.3-loading-json-data.html`\n\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml lang=\"en\"\u003e\n\n \u003chead\u003e\n \u003cmeta charset=\"UTF-8\"\u003e\n \u003cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"\u003e\n \u003cmeta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"\u003e\n \u003ctitle\u003eloading json data\u003c/title\u003e\n \n \u003cscript type=\"text/javascript\" src=\"2.3-loading-json-data.js\"\u003e\u003c/script\u003e\n\n \u003c/head\u003e\n\n \u003cbody\u003e\n \n \u003c/body\u003e\n\n\u003c/html\u003e\n```\n\n\u003chr/\u003e\n\n\u003e **Syntax \u0026 Example**: `2.3-loading-json-data.js`\n\n```js\nconsole.log('2.3-loading-json-data.js loaded');\n\nvar xhr = new XMLHttpRequest();\nxhr.open('GET','animals1.json');\n\nxhr.onload = function() {\n let results = xhr.responseText;\n console.log('string type of json:',results);\n document.write('\u003ch1\u003eLoad JSON data from .json file:\u003c/h1\u003e');\n document.write(results);\n\n results = JSON.parse(xhr.responseText);\n console.log('json object after parsing:',results);\n \n document.write('\u003ch2\u003eLoad 0 th animal details:\u003c/h2\u003e');\n var animal0 = results[0].name;\n document.write('Name : ' + animal0);\n}\n\nxhr.send();\n```\n\n\u003e **Note**: *Its advisable to use local web-server like XAMP, MAMP or node/npm server utilities-packages like serve, http-server, static, local-web-server to avoid any - **CORS policy: Cross-origin requests errors***\n\n\n2.4. XMLHttpRequest-loading web API data\n--------------------- \n\nJSON Web API path: https://learnwebcode.github.io/json-example/animals-1.json\n\n\u003e **Syntax \u0026 Example**: `1.6.1-employee.json`\n\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml lang=\"en\"\u003e\n\n \u003chead\u003e\n \u003cmeta charset=\"UTF-8\"\u003e\n \u003cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"\u003e\n \u003cmeta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"\u003e\n \u003ctitle\u003eloading web API data\u003c/title\u003e\n \n \u003cscript type=\"text/javascript\" src=\"2.4-loading-json-web-api-data.js\"\u003e\u003c/script\u003e\n\n \u003c/head\u003e\n\n \u003cbody\u003e\n \n \u003c/body\u003e\n\n\u003c/html\u003e\n```\n\n\u003chr/\u003e\n\n\u003e **Syntax \u0026 Example**: `2.4-loading-json-web-api-data.js`\n\n```js\nconsole.log('2.4-loading-json-web-api-data.js loaded');\n\nvar xhr = new XMLHttpRequest();\nxhr.open('GET','https://learnwebcode.github.io/json-example/animals-1.json');\n\nxhr.onload = function() {\n let results = xhr.responseText;\n console.log('string type of json:',results);\n document.write('\u003ch1\u003eLoad JSON data from .json file:\u003c/h1\u003e');\n document.write(results);\n\n results = JSON.parse(xhr.responseText);\n console.log('json object after parsing:',results);\n \n document.write('\u003ch2\u003eLoad 1 st animal details:\u003c/h2\u003e');\n var animal1 = results[1].name;\n document.write('Name : ' + animal1);\n}\n\nxhr.send(); \n```\n\n\n2.5. GET vs POST method\n---------------------\n\n| Points | GET method | POST method | \n| ------------------------------- | ------------------------------- | ------------------------------- |\n| **`Send data visibility`** \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; \u0026nbsp; | GET sends data in open/visible mode in browser URL as a parameter | GET sends data in invisible/hidden (secure) mode |\n| **`Encoding type`** | application/x-www-form-urlencoded | multipart/form-data or application/x-www-form-urlencoded Use multipart encoding for binary data |\n| **`Secure`** | GET is better for non-secure data, like id/filter string parameters, query strings in Google, etc. | GET is better for secure/passing important-sensitive data, like Auth-Authorisation, password, keys, etc. |\n| **`Data size`** | Sends data less than 2K of parameters, some servers handle up to 64K | Sending a large amount of data to the server (POST has no size limitations) | \n| **`Security`** | GET is less secure as compared to POST because data sent is part of the URL. So it's saved in browser history and server logs in plaintext | POST is a more safer than GET method because the parameters are not stored in browser history or web server logs | \n| **`Cached`** | Can be cached | Can not be cached |\n| **`Usability`** | GET method can be used for sending data parameters (should not be used when sending passwords or other sensitive information) | POST method used when sending Auth-Authorisation, passwords or other sensitive information |\n| **`Form data length restrictions`** | As data is in the URL and URL length is restricted, A safe URL length limit is often 2048 characters but varies by browser and web server | No data length and data size restrictions | \n| **`Form data type restrictions`** | Only ASCII characters allowed | No restrictions! Binary data is also allowed | \n| **`Hacked`** | Easier to hack for script kiddies, computer attackers or hackers | Difficult to hack |\n| **`Bookmarked`** | Can be bookmarked | Can be bookmarked |\n| **`Form method`** | GET is the default method in the form element | To use POST we need to specify it in HTML Forms as `method=\"POST\"` |\n\n\n2.6. XMLHttpRequest-onreadystatechange\n---------------------\n\n### 2.6.1. XMLHttpRequest-onreadystatechange property\n- The XMLHttpRequest object has a special property called `onreadystatechange`\n- `onreadystatechange` stores the function that will process the response from the server\n- The `XMLHttpRequest.onreadystatechange` property stores a function, contains the event handler to be called when the `readystatechange` event is fired, that is every time the `readyState` property of the XMLHttpRequest changes\n\n### 2.6.2. XMLHttpRequest-readystate property\n\n- The `XMLHttpRequest` object has another property called `readyState`\n- `readyState` is where the status of our server's response is stored \n- Each time the `readyState` changes then our `onreadystatechange` function executes, The response can be:\n - processing, \n - downloading or \n - completed\n\n| Property | Description | \n| ------------------------------- | ------------------------------- |\n| onreadystatechange | Defines a function to be called when the readyState property changes |\n| readyState | Holds/Stores the status of the XMLHttpRequest, readyState Status can be: \u003cli\u003e0: request not initialized\u003c/li\u003e \u003cli\u003e1: server connection established\u003c/li\u003e \u003cli\u003e2: request received\u003c/li\u003e \u003cli\u003e3: processing request\u003c/li\u003e \u003cli\u003e4: request finished and response is ready\u003c/li\u003e | \n| status | The status property and the statusText property holds the status of the XMLHttpRequest object, Status can be: \u003cli\u003e200: \"OK\"\u003c/li\u003e \u003cli\u003e403: \"Forbidden\"\u003c/li\u003e \u003cli\u003e404: \"Page not found\"\u003c/li\u003e |\n| statusText | The status property and the statusText property holds the status of the XMLHttpRequest object, Returns the status-text (e.g. \"OK\" or \"Not Found\") |\n\n\u003e **Note**: When the property `readyState is 4` that means the response is complete and we can get our data\n\n### 2.6.3. XMLHttpRequest-responsetext property\n\n- We can retrieve the server's response by using the `responseText` property\n- Using a little bit of Javascript and HTML forms we can change our text box or results equal responseText\n\n\n\u003e **Syntax \u0026 Example**: `2.6-onreadystatechange.html`\n\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml lang=\"en\"\u003e\n\n \u003chead\u003e\n \u003cmeta charset=\"UTF-8\"\u003e\n \u003cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"\u003e\n \u003cmeta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"\u003e\n \u003ctitle\u003eonreadystatechange\u003c/title\u003e\n \n \u003cscript type=\"text/javascript\" src=\"2.6-onreadystatechange.js\"\u003e\u003c/script\u003e\n\n \u003c/head\u003e\n\n \u003cbody\u003e\n\n \u003ch1\u003eThe XMLHttpRequest Object - onreadystatechange\u003c/h1\u003e\n\n \u003cbutton type=\"button\" onclick=\"loadData()\"\u003eLoad Content\u003c/button\u003e\n \n \u003cdiv id=\"textContainer\"\u003e\u003c/div\u003e\n\n \u003c/body\u003e\n\n\u003c/html\u003e\n```\n\n\u003chr/\u003e\n\n\u003e **Syntax \u0026 Example**: `2.6-onreadystatechange.js`\n\n```js\nconsole.log('2.6-onreadystatechange.js loaded');\n\nfunction loadData() {\n\n var xhr = new XMLHttpRequest();\n xhr.open('GET','data.txt',true);\n\n xhr.onreadystatechange = function() {\n if(this.readyState == 4 \u0026\u0026 this.status == 200) {\n // responseText and response both are same/similar\n let responseText = xhr.responseText;\n let response = xhr.response;\n console.log('responseText',responseText);\n console.log('response',response);\n\n // document.getElementById(\"textContainer\").innerHTML = this.responseText;\n document.getElementById(\"textContainer\").innerText = this.responseText;\n\n }\n }\n\n xhr.send();\n\n}\n\n```\n\n\u003chr/\u003e\n\n\u003e **Syntax \u0026 Example**: `data.txt`\n\n```\n\u003ch3\u003e### 2.6.1. XMLHttpRequest-onreadystatechange property\u003c/h3\u003e\n\n\u003cli\u003eThe XMLHttpRequest object has a special property called `onreadystatechange`\u003c/li\u003e\n\n\u003cli\u003e`onreadystatechange` stores the function that will process the response from the server\u003c/li\u003e\n\n\u003cli\u003eThe `XMLHttpRequest.onreadystatechange` property stores a function, contains the event handler to be called when the `readystatechange` event is fired, that is every time the `readyState` property of the XMLHttpRequest changes\u003c/li\u003e\n```\n\n\n3 AJAX Live Demo Example\n=====================\n\n3.1. XMLHttpRequest-Get Post Data-Basic\n---------------------\n\n\u003e **Syntax \u0026 Example**: `3.1-xhr-req-res-live.html`\n\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml lang=\"en\"\u003e\n\n  \u003chead\u003e\n    \u003cmeta charset=\"UTF-8\"\u003e\n    \u003cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"\u003e\n    \u003cmeta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"\u003e\n    \u003ctitle\u003e3.1-xhr-req-res-live.html\u003c/title\u003e\n    \n    \u003clink type=\"text/css\" rel=\"stylesheet\" href=\"styles.css\"\u003e\n    \u003c!-- Without async or defer , browser will run your script immediately, before rendering the elements that's below your script tag. --\u003e\n    \u003cscript type=\"text/javascript\" src=\"3.1-xhr-req-res-live.js\" defer\u003e\u003c/script\u003e\n\n  \u003c/head\u003e\n\n  \u003cbody\u003e\n\n    \u003csection class=\"button-container\"\u003e\n      \u003cbutton id=\"getButton\" class=\"button\"\u003eGET DATA\u003c/button\u003e\n      \u003cbutton id=\"postButton\" class=\"button\"\u003ePOST LOGIN DATA\u003c/button\u003e\n    \u003c/section\u003e\n   \n  \u003c/body\u003e\n\n\u003c/html\u003e\n```\n\n\u003chr/\u003e\n\n\u003e **Syntax \u0026 Example**: `3.1-xhr-req-res-live.js`\n\n```js\nconsole.log('3.1-xhr-req-res-live.js loaded');\n\n// get buttons from html/DOM\nconst getButton = document.getElementById('getButton');\nconst postButton = document.getElementById('postButton');\n\n// define function to get data\nfn_getData = () =\u003e {\n  console.log('getButton clicked - in fn_getData');\n\n  var xhr = new XMLHttpRequest();\n  // use fake rest api `https://reqres.in/`, below url get list of users\n  xhr.open('GET', 'https://reqres.in/api/users');\n\n  // convert XMLHttpRequest results to 'json' bydefault\n  xhr.responseType = 'json';\n\n  xhr.onload = () =\u003e {\n    let results = xhr.response;\n    console.log('results:', results);\n\n    //convert string data to json/javascript object - ommit by using xhe.responseType = 'json'\n    // const jsonData = JSON.parse(results);\n    // console.log('jsonData:', jsonData);\n  }\n\n  xhr.send();\n}\n\n// define function to post/send data\nfn_postData = () =\u003e {\n  console.log('postButton clicked - in fn_postData');\n\n  const postData = {\n    \"email\": \"eve.holt@reqres.in\",\n    \"password\": \"pistol\"\n  };\n\n  var xhr = new XMLHttpRequest();\n  // use fake rest api `https://reqres.in/`, below url get list of users\n  xhr.open('POST', 'https://reqres.in/api/register');\n\n  // convert XMLHttpRequest results to 'json' bydefault\n  // xhr.responseType = 'json';\n  xhr.setRequestHeader(\"Content-Type\", \"application/json; charset=UTF-8\");\n\n  xhr.onload = function () {\n    var results = JSON.parse(xhr.responseText);\n    console.log(results);\n\n  };\n\n  xhr.send((JSON.stringify(postData)));\n}\n\n// add event listener to button\ngetButton.addEventListener('click', fn_getData);\npostButton.addEventListener('click', fn_postData);\n```\n\n\n3.2. XMLHttpRequest-Get Post Data-Advanced\n---------------------\n\n\u003e **Syntax \u0026 Example**: `3.2-xhr-req-res-live-advanced.html`\n\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml lang=\"en\"\u003e\n\n  \u003chead\u003e\n    \u003cmeta charset=\"UTF-8\"\u003e\n    \u003cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"\u003e\n    \u003cmeta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"\u003e\n    \u003ctitle\u003e3.2-xhr-req-res-live-advanced.html\u003c/title\u003e\n    \n    \u003clink type=\"text/css\" rel=\"stylesheet\" href=\"styles.css\"\u003e\n    \u003c!-- Without async or defer , browser will run your script immediately, before rendering the elements that's below your script tag. --\u003e\n    \u003cscript type=\"text/javascript\" src=\"3.2-xhr-req-res-live-advanced.js\" defer\u003e\u003c/script\u003e\n\n  \u003c/head\u003e\n\n  \u003cbody\u003e\n\n    \u003csection class=\"button-container\"\u003e\n      \u003cbutton id=\"getButton\" class=\"button\"\u003eGET DATA\u003c/button\u003e\n      \u003cbutton id=\"postButton\" class=\"button\"\u003ePOST LOGIN DATA\u003c/button\u003e\n    \u003c/section\u003e\n\n    \u003csection class=\"user-container\"\u003e\n      \u003ch1 class=\"user-name\"\u003e\u003c/h1\u003e\n      \u003cspan class=\"user-email\"\u003e\u003c/span\u003e \u003cbr/\u003e \u003cbr/\u003e\n      \u003cimg class=\"user-image\" src=\" \" /\u003e\n    \u003c/section\u003e\n   \n  \u003c/body\u003e\n\n\u003c/html\u003e\n```\n\n\u003chr/\u003e\n\n\u003e **Syntax \u0026 Example**: `3.2-xhr-req-res-live-advanced.js`\n\n```js\nconsole.log('3.2-xhr-req-res-live-advanced.js loaded');\n\n// get buttons from html/DOM\nconst getButton = document.getElementById('getButton');\nconst postButton = document.getElementById('postButton');\n\n// common function to send receive http call\nconst fn_sendhttpRequest = (httpMethod, httpUrl, data) =\u003e {\n  // promise\n  const httpPromise = new Promise((resolve, reject) =\u003e {\n\n    const xhr = new XMLHttpRequest();\n\n    // use fake rest api `https://reqres.in/`, below url get list of users\n    xhr.open(httpMethod, httpUrl);\n\n    // convert XMLHttpRequest results to 'json' bydefault\n    xhr.responseType = 'json';\n\n    if (data) {\n      xhr.setRequestHeader(\"Content-Type\", \"application/json; charset=UTF-8\");\n    }\n\n    xhr.onload = () =\u003e {\n      if (xhr.status \u003e= 400) {\n        reject(xhr.response);\n      } else {\n        resolve(xhr.response);\n      }\n    }\n\n    xhr.onerror = () =\u003e {\n      reject('Please verify...something went wrong!');\n    }\n\n    xhr.send(JSON.stringify(data));\n\n  });\n\n  return httpPromise;\n\n}\n\n// define function to get data\nconst fn_getData = () =\u003e {\n  console.log('getButton clicked - in fn_getData');\n\n  fn_sendhttpRequest('GET', 'https://reqres.in/api/users').then(respenseResultData =\u003e {\n    console.log('respenseResultData:', respenseResultData);\n    document.getElementsByClassName('user-name')[0].innerHTML = respenseResultData.data[0].first_name + ' ' + respenseResultData.data[0].last_name;\n    document.getElementsByClassName('user-email')[0].innerHTML = respenseResultData.data[0].email;\n    document.getElementsByClassName('user-image')[0].src = respenseResultData.data[0].avatar;\n  });\n\n}\n\n// define function to post/send data\nconst fn_postData = () =\u003e {\n  console.log('postButton clicked - in fn_postData');\n\n  const postLoginData = {\n    \"email\": \"eve.holt@reqres.in\",\n    \"password\": \"pistol\"\n  };\n\n  fn_sendhttpRequest('POST', 'https://reqres.in/api/register', postLoginData).then(respenseResultData =\u003e {\n    console.log('respenseResultData:', respenseResultData);\n  }).catch(err =\u003e {\n    console.log('errors: ', err);\n  });\n\n}\n\n// add event listener to button\ngetButton.addEventListener('click', fn_getData);\npostButton.addEventListener('click', fn_postData);\n```\n\n\n4 JavaScript Http Request with fetch() API and Promises\n=====================\n\n4.1. Introduction to fetch() API\n---------------------\n- Fetch is a new, modern, promise-based API that lets us do Ajax requests without all the unnecessary complications associated with XMLHttpRequest\n- `fetch() API` is a modern replacement for XMLHttpRequest, addition to the browser, better than xmlHttpRequest \n- fetch API, which is a modern way to Ajax without helper libraries like jQuery or Axios\n- The Fetch API provides a fetch() method defined on the window object, which you can use to perform requests. This method returns a Promise that you can use to retrieve the response of the request\n- `fetch()` is the globally available method/function made available/provided by the browser for sending http-request\n- Browser support: Support for Fetch is pretty good! All major browsers (exception of Opera Mini and old IE) support it natively, which means we can safely use it in our projects (older browser does not support!)\n\n\n4.2. fetch() API demo example\n---------------------\n\n\u003e **Syntax \u0026 Example**: `4.2-fetch-api.html`\n\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml lang=\"en\"\u003e\n\n  \u003chead\u003e\n    \u003cmeta charset=\"UTF-8\"\u003e\n    \u003cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"\u003e\n    \u003cmeta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"\u003e\n    \u003ctitle\u003e4.2-fetch-api\u003c/title\u003e\n    \n    \u003clink type=\"text/css\" rel=\"stylesheet\" href=\"styles.css\"\u003e\n    \u003c!-- Without async or defer , browser will run your script immediately, before rendering the elements that's below your script tag. --\u003e\n    \u003cscript type=\"text/javascript\" src=\"4.2-fetch-api.js\" defer\u003e\u003c/script\u003e\n\n  \u003c/head\u003e\n\n  \u003cbody\u003e\n\n    \u003csection class=\"button-container\"\u003e\n      \u003cbutton id=\"getButton\" class=\"button\"\u003eGET DATA\u003c/button\u003e\n      \u003cbutton id=\"postButton\" class=\"button\"\u003ePOST LOGIN DATA\u003c/button\u003e\n    \u003c/section\u003e\n\n    \u003csection class=\"user-container\"\u003e\n      \u003ch1 class=\"user-name\"\u003e\u003c/h1\u003e\n      \u003cspan class=\"user-email\"\u003e\u003c/span\u003e \u003cbr/\u003e \u003cbr/\u003e\n      \u003cimg class=\"user-image\" src=\" \" /\u003e\n    \u003c/section\u003e\n   \n  \u003c/body\u003e\n\n\u003c/html\u003e\n```\n\n\u003chr/\u003e\n\n\u003e **Syntax \u0026 Example**: `4.2-fetch-api.js`\n\n```javascript\nconsole.log('4.2-fetch-api.js loaded');\n\n// get buttons from html/DOM\nconst getButton = document.getElementById('getButton');\nconst postButton = document.getElementById('postButton');\n\n// define function to get data\nconst fn_getData = () =\u003e {\n  console.log('getButton clicked - in fn_getData');\n\n  fetch('https://reqres.in/api/users').then(respenseResult =\u003e {\n    console.log('respenseResult:', respenseResult);\n    // to convert response body: ReadableStream to json\n    return respenseResult.json();\n  })\n  .then(respenseResultData =\u003e {\n    console.log('respenseResultData:', respenseResultData);\n\n    document.getElementsByClassName('user-name')[0].innerHTML = respenseResultData.data[0].first_name + ' ' + respenseResultData.data[0].last_name;\n    document.getElementsByClassName('user-email')[0].innerHTML = respenseResultData.data[0].email;\n    document.getElementsByClassName('user-image')[0].src = respenseResultData.data[0].avatar;\n  });\n}\n\n// define function to post/send data\nconst fn_postData = () =\u003e {\n  console.log('postButton clicked - in fn_postData');\n\n  const options = {\n    method: 'post',\n    headers: {\n      'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'\n    },\n    body: 'email=eve.holt@reqres.in\u0026password=pistol'\n  }\n  \n  fetch('https://reqres.in/api/register', options)\n  .then(respenseResult =\u003e {\n    console.log('respenseResult:', respenseResult);\n    return respenseResult.json();\n  })\n  .then(respenseResultData =\u003e {\n    console.log('respenseResultData:', respenseResultData);\n  })\n  .catch(err =\u003e {\n    console.error('Request failed', err)\n  })\n\n}\n\n// add event listener to button\ngetButton.addEventListener('click', fn_getData);\npostButton.addEventListener('click', fn_postData);\n```\n\n\u003chr/\u003e\n\n\u003e **Syntax \u0026 Example**: `4.2-fetch-api-advanced.html`\n\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml lang=\"en\"\u003e\n\n  \u003chead\u003e\n    \u003cmeta charset=\"UTF-8\"\u003e\n    \u003cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"\u003e\n    \u003cmeta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"\u003e\n    \u003ctitle\u003e4.2-fetch-api-advanced\u003c/title\u003e\n    \n    \u003clink type=\"text/css\" rel=\"stylesheet\" href=\"styles.css\"\u003e\n    \u003c!-- Without async or defer , browser will run your script immediately, before rendering the elements that's below your script tag. --\u003e\n    \u003cscript type=\"text/javascript\" src=\"4.2-fetch-api-advanced.js\" defer\u003e\u003c/script\u003e\n\n  \u003c/head\u003e\n\n  \u003cbody\u003e\n\n    \u003ch1\u003e\u003ccenter\u003e4.2-fetch-api-advanced\u003c/center\u003e\u003c/h1\u003e\n    \u003csection class=\"button-container\"\u003e\n      \u003cbutton id=\"getButton\" class=\"button\"\u003eGET DATA\u003c/button\u003e\n      \u003cbutton id=\"postButton\" class=\"button\"\u003ePOST LOGIN DATA\u003c/button\u003e\n    \u003c/section\u003e\n\n    \u003csection class=\"user-container\"\u003e\n      \u003ch1 class=\"user-name\"\u003e\u003c/h1\u003e\n      \u003cspan class=\"user-email\"\u003e\u003c/span\u003e \u003cbr/\u003e \u003cbr/\u003e\n      \u003cimg class=\"user-image\" src=\" \" /\u003e\n    \u003c/section\u003e\n   \n  \u003c/body\u003e\n\n\u003c/html\u003e\n```\n\n\u003chr/\u003e\n\n\u003e **Syntax \u0026 Example**: `4.2-fetch-api-advanced.js`\n\n```javascript\nconsole.log('4.2-fetch-api-advanced.js loaded');\n\n// get buttons from html/DOM\nconst getButton = document.getElementById('getButton');\nconst postButton = document.getElementById('postButton');\n\n// common function to send receive http call\nconst fn_sendhttpRequest = (httpMethod, httpUrl, data) =\u003e {\n\n  return fetch(httpUrl, {\n    method: httpMethod,\n    body: JSON.stringify(data),\n    headers: data ? {'Content-type': 'application/json'} : {}\n  }).then(respenseResult =\u003e { \n    console.log('respenseResult:', respenseResult);\n    if (respenseResult.status \u003e= 400) {\n      return respenseResult.json().then(errResponseData =\u003e {\n        const error = new Error('Please verify...something went wrong!');\n        error.data = errResponseData;\n        throw error;\n      })\n    }\n    // to convert response body: ReadableStream to json\n    return respenseResult.json();\n  })\n\n}\n\n// define function to get data\nconst fn_getData = () =\u003e {\n  console.log('getButton clicked - in fn_getData');\n\n  fn_sendhttpRequest('GET', 'https://reqres.in/api/users')\n  .then(respenseResultData =\u003e {\n    console.log('respenseResultData:', respenseResultData);\n\n    document.getElementsByClassName('user-name')[0].innerHTML = respenseResultData.data[0].first_name + ' ' + respenseResultData.data[0].last_name;\n    document.getElementsByClassName('user-email')[0].innerHTML = respenseResultData.data[0].email;\n    document.getElementsByClassName('user-image')[0].src = respenseResultData.data[0].avatar;\n  });\n\n}\n\n// define function to post/send data\nconst fn_postData = () =\u003e {\n  console.log('postButton clicked - in fn_postData');\n\n  const postLoginData = {\n    email: \"eve.holt@reqres.in\",\n    password: \"pistol\"\n  };\n\n  fn_sendhttpRequest('POST', 'https://reqres.in/api/register', postLoginData)\n  .then(respenseResultData =\u003e {\n    console.log('respenseResultData:', respenseResultData);\n  })\n  .catch(err =\u003e {\n    console.error('Request failed', err)\n  })\n\n}\n\n// add event listener to button\ngetButton.addEventListener('click', fn_getData);\npostButton.addEventListener('click', fn_postData);\n```\n\n5 JavaScript Http Request with Axios library\n=====================\n\n5.1. Introduction to Axios\n---------------------\n\n- Axios is an open-source library that allows us to easily make HTTP requests\n- Axios is a third-party JavaScript library which wraps xmlHttpRequest, based on Promise API and makes working with AJAX much easier\n- Axios is a Promise-based HTTP client for JavaScript which can be used in your front-end application, also in Node.js backend\n- Browser support: It supports all modern browsers, including support for IE8 and higher! All major browsers support it, as xmlHttpRequest is the base of Axios\n\n\n5.2. Axios demo example\n---------------------\n\n\u003e **Syntax \u0026 Example**: `5.2-axios.html`\n\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml lang=\"en\"\u003e\n\n  \u003chead\u003e\n    \u003cmeta charset=\"UTF-8\"\u003e\n    \u003cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"\u003e\n    \u003cmeta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"\u003e\n    \u003ctitle\u003e5.2-axios\u003c/title\u003e\n    \n    \u003clink type=\"text/css\" rel=\"stylesheet\" href=\"styles.css\"\u003e\n    \u003cscript type=\"text/javascript\" src=\"axios.min.js\" defer\u003e\u003c/script\u003e\n    \u003c!-- Without async or defer , browser will run your script immediately, before rendering the elements that's below your script tag. --\u003e\n    \u003cscript type=\"text/javascript\" src=\"5.2-axios.js\" defer\u003e\u003c/script\u003e\n\n  \u003c/head\u003e\n\n  \u003cbody\u003e\n\n    \u003ch1\u003e\u003ccenter\u003e5.2-axios\u003c/center\u003e\u003c/h1\u003e\n    \u003csection class=\"button-container\"\u003e\n      \u003cbutton id=\"getButton\" class=\"button\"\u003eGET DATA\u003c/button\u003e\n      \u003cbutton id=\"postButton\" class=\"button\"\u003ePOST LOGIN DATA\u003c/button\u003e\n    \u003c/section\u003e\n\n    \u003csection class=\"user-container\"\u003e\n      \u003ch1 class=\"user-name\"\u003e\u003c/h1\u003e\n      \u003cspan class=\"user-email\"\u003e\u003c/span\u003e \u003cbr/\u003e \u003cbr/\u003e\n      \u003cimg class=\"user-image\" src=\" \" /\u003e\n    \u003c/section\u003e\n   \n  \u003c/body\u003e\n\n\u003c/html\u003e\n```\n\n\u003chr/\u003e\n\n\u003e **Syntax \u0026 Example**: `5.2-axios.js`\n\n```javascript\nconsole.log('5.2-axios.js loaded');\n\n// get buttons from html/DOM\nconst getButton = document.getElementById('getButton');\nconst postButton = document.getElementById('postButton');\n\n// define function to get data\nconst fn_getData = () =\u003e {\n  console.log('getButton clicked - in fn_getData');\n\n  axios.get('https://reqres.in/api/users').then(respenseResultData =\u003e {\n    console.log('respenseResultData:', respenseResultData);\n\n    document.getElementsByClassName('user-name')[0].innerHTML = respenseResultData.data.data[0].first_name + ' ' + respenseResultData.data.data[0].last_name;\n    document.getElementsByClassName('user-email')[0].innerHTML = respenseResultData.data.data[0].email;\n    document.getElementsByClassName('user-image')[0].src = respenseResultData.data.data[0].avatar;\n  })\n\n}\n\n// define function to post/send data\nconst fn_postData = () =\u003e {\n  console.log('postButton clicked - in fn_postData');\n\n  const postLoginData = {\n    email: \"eve.holt@reqres.in\",\n    password: \"pistol\"\n  };\n\n  axios.post('https://reqres.in/api/register', postLoginData, {\n    headers: {\n      'Content-type': 'application/json'\n    }\n  }).then(respenseResultData =\u003e {\n    console.log('respenseResultData:', respenseResultData);\n    console.log('respenseResultData.data:', respenseResultData.data);\n  }).catch(err =\u003e {\n    console.error('Request failed...Something went wrong :', err);\n    console.error(err, err.response.data);\n  })\n\n}\n\n// add event listener to button\ngetButton.addEventListener('click', fn_getData);\npostButton.addEventListener('click', fn_postData);\n```\n\n\n6 AJAX Reference and Resources\n=====================\n\n\u003e https://reqres.in/\n\n\u003e axios - https://github.com/axios/axios\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdinanathsj29%2Fajax-asynchronous-javascript-and-xml-course-tutorial","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdinanathsj29%2Fajax-asynchronous-javascript-and-xml-course-tutorial","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdinanathsj29%2Fajax-asynchronous-javascript-and-xml-course-tutorial/lists"}