- Javascript Basics Tutorial
- Javascript - Home
- JavaScript - Overview
- JavaScript - Features
- JavaScript - Enabling
- JavaScript - Placement
- JavaScript - Syntax
- JavaScript - Hello World
- JavaScript - Console.log()
- JavaScript - Comments
- JavaScript - Variables
- JavaScript - let Statement
- JavaScript - Constants
- JavaScript - Data Types
- JavaScript - Type Conversions
- JavaScript - Strict Mode
- JavaScript - Reserved Keywords
- JavaScript Operators
- JavaScript - Operators
- JavaScript - Arithmetic Operators
- JavaScript - Comparison Operators
- JavaScript - Logical Operators
- JavaScript - Bitwise Operators
- JavaScript - Assignment Operators
- JavaScript - Conditional Operators
- JavaScript - typeof Operator
- JavaScript - Nullish Coalescing Operator
- JavaScript - Delete Operator
- JavaScript - Comma Operator
- JavaScript - Grouping Operator
- JavaScript - Yield Operator
- JavaScript - Spread Operator
- JavaScript - Exponentiation Operator
- JavaScript - Operator Precedence
- JavaScript Control Flow
- JavaScript - If...Else
- JavaScript - While Loop
- JavaScript - For Loop
- JavaScript - For...in
- Javascript - For...of
- JavaScript - Loop Control
- JavaScript - Break Statement
- JavaScript - Continue Statement
- JavaScript - Switch Case
- JavaScript - User Defined Iterators
- JavaScript Functions
- JavaScript - Functions
- JavaScript - Function Expressions
- JavaScript - Function Parameters
- JavaScript - Default Parameters
- JavaScript - Function() Constructor
- JavaScript - Function Hoisting
- JavaScript - Self-Invoking Functions
- JavaScript - Arrow Functions
- JavaScript - Function Invocation
- JavaScript - Function call()
- JavaScript - Function apply()
- JavaScript - Function bind()
- JavaScript - Closures
- JavaScript - Variable Scope
- JavaScript - Global Variables
- JavaScript - Smart Function Parameters
- JavaScript Objects
- JavaScript - Number
- JavaScript - Boolean
- JavaScript - Strings
- JavaScript - Arrays
- JavaScript - Date
- JavaScript - DataView
- JavaScript - Math
- JavaScript - RegExp
- JavaScript - Symbol
- JavaScript - Sets
- JavaScript - WeakSet
- JavaScript - Maps
- JavaScript - WeakMap
- JavaScript - Iterables
- JavaScript - Reflect
- JavaScript - TypedArray
- JavaScript - Template Literals
- JavaScript - Tagged Templates
- Object Oriented JavaScript
- JavaScript - Objects
- JavaScript - Classes
- JavaScript - Object Properties
- JavaScript - Object Methods
- JavaScript - Static Methods
- JavaScript - Display Objects
- JavaScript - Object Accessors
- JavaScript - Object Constructors
- JavaScript - Native Prototypes
- JavaScript - ES5 Object Methods
- JavaScript - Encapsulation
- JavaScript - Inheritance
- JavaScript - Abstraction
- JavaScript - Polymorphism
- JavaScript - Destructuring Assignment
- JavaScript - Object Destructuring
- JavaScript - Array Destructuring
- JavaScript - Nested Destructuring
- JavaScript - Optional Chaining
- JavaScript - Global Object
- JavaScript - Mixins
- JavaScript - Proxies
- JavaScript Versions
- JavaScript - History
- JavaScript - Versions
- JavaScript - ES5
- JavaScript - ES6
- ECMAScript 2016
- ECMAScript 2017
- ECMAScript 2018
- ECMAScript 2019
- ECMAScript 2020
- ECMAScript 2021
- ECMAScript 2022
- JavaScript Cookies
- JavaScript - Cookies
- JavaScript - Cookie Attributes
- JavaScript - Deleting Cookies
- JavaScript Browser BOM
- JavaScript - Browser Object Model
- JavaScript - Window Object
- JavaScript - Document Object
- JavaScript - Screen Object
- JavaScript - History Object
- JavaScript - Navigator Object
- JavaScript - Location Object
- JavaScript - Console Object
- JavaScript Web APIs
- JavaScript - Web API
- JavaScript - History API
- JavaScript - Storage API
- JavaScript - Forms API
- JavaScript - Worker API
- JavaScript - Fetch API
- JavaScript - Geolocation API
- JavaScript Events
- JavaScript - Events
- JavaScript - DOM Events
- JavaScript - addEventListener()
- JavaScript - Mouse Events
- JavaScript - Keyboard Events
- JavaScript - Form Events
- JavaScript - Window/Document Events
- JavaScript - Event Delegation
- JavaScript - Event Bubbling
- JavaScript - Event Capturing
- JavaScript - Custom Events
- JavaScript Error Handling
- JavaScript - Error Handling
- JavaScript - try...catch
- JavaScript - Debugging
- JavaScript - Custom Errors
- JavaScript - Extending Errors
- JavaScript Important Keywords
- JavaScript - this Keyword
- JavaScript - void Keyword
- JavaScript - new Keyword
- JavaScript - var Keyword
- JavaScript HTML DOM
- JavaScript - HTML DOM
- JavaScript - DOM Methods
- JavaScript - DOM Document
- JavaScript - DOM Elements
- JavaScript - DOM Forms
- JavaScript - Changing HTML
- JavaScript - Changing CSS
- JavaScript - DOM Animation
- JavaScript - DOM Navigation
- JavaScript - DOM Collections
- JavaScript - DOM Node Lists
- JavaScript Miscellaneous
- JavaScript - Ajax
- JavaScript - Async Iteration
- JavaScript - Atomics Objects
- JavaScript - Rest Parameter
- JavaScript - Page Redirect
- JavaScript - Dialog Boxes
- JavaScript - Page Printing
- JavaScript - Validations
- JavaScript - Animation
- JavaScript - Multimedia
- JavaScript - Image Map
- JavaScript - Browsers
- JavaScript - JSON
- JavaScript - Multiline Strings
- JavaScript - Date Formats
- JavaScript - Get Date Methods
- JavaScript - Set Date Methods
- JavaScript - Modules
- JavaScript - Dynamic Imports
- JavaScript - BigInt
- JavaScript - Blob
- JavaScript - Unicode
- JavaScript - Shallow Copy
- JavaScript - Call Stack
- JavaScript - Reference Type
- JavaScript - IndexedDB
- JavaScript - Clickjacking Attack
- JavaScript - Currying
- JavaScript - Graphics
- JavaScript - Canvas
- JavaScript - Debouncing
- JavaScript - Performance
- JavaScript - Style Guide
- JavaScript Useful Resources
- JavaScript - Questions And Answers
- JavaScript - Quick Guide
- JavaScript - Functions
- JavaScript - Resources
JavaScript - Ajax
Asynchronous JavaScript and XML (Ajax) represents a web development technique: it enables dynamic, interactive communication between server and webpage without necessitating complete page reload. The descriptor "asynchronous" underlines that data exchanges can occur in the background, independent of user experience disruption. Rather than idly awaiting full-page refreshment; Ajax empowers real-time updates on specific sections of a webpage, thus yielding an interface that is more seamless and responsive.
How Ajax works?
The central role in enabling dynamic updates, without the necessity of a full page reload, belongs to the XMLHttpRequest object within JavaScript's Ajax functionality. This particular process allows for asynchronous communication between server and web page. The server responds with data, usually in JSON or XML format when receiving a request sent by this object. Processing this data is the task of JavaScript; it updates specific portions of the webpage in real-time. The asynchronous nature which is a critical feature for modern web development ensures these operations occur unobtrusively in background, thereby enhancing interactivity by allowing data to be fetched and sent asynchronously.
Here, we will to explore Ajax to get a deeper understanding of it.
There are 4 approaches to make Ajax calls or to implement Ajax in JavaScript and they are:
XMLHttpRequest (Older Approach)
Fetch API (Modern Approach)
Axios (Library for HTTP Requests)
jQuery Ajax
We will be using JSONPlaceholder in all the examples for understanding purposes.
JSONPlaceholder is an open-source and simulated REST API provider which lets developers test their prototype applications. It returns fake/dummy data for various resources like users, posts, comments etc. The API endpoints of JSONPlaceholder can be made using HTTP requests and they will be mimicking the nature of real APIs without any need for authentication. Our goal here is to use these APIs/endpoints to under Javascript-Ajax.
Using XMLHttpRequest
The Native JavaScript approach using XMLHttpRequest represents the oldest method for asynchronous requests. It relies on the XMLHttpRequest object to create and send HTTP requests. This method involves setting up callback functions to handle various states of the request, making it suitable for simpler scenarios. However, it has some limitations compared to more modern approaches.
Example
<!DOCTYPE html> <html lang="en"> <body> <p>Native XMLHttpRequest Example</p> <button onclick="nativeAjax()">Make Request</button> <pre id="result"></pre> <script> function nativeAjax() { var xhr = new XMLHttpRequest(); xhr.open('GET', 'https://jsonplaceholder.typicode.com/users/2', true); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { var responseData = JSON.stringify(JSON.parse(xhr.responseText), null, 2); document.getElementById('result').innerText = 'Native XMLHttpRequest:\n' + responseData; } }; xhr.send(); } </script> </body> </html>
Using Fetch API
Presenting a modern alternative to XMLHttpRequest, the Fetch API offers a more straightforward and powerful syntax; it returns Promises thus enhancing the intuitive handling of asynchronous operations. Supporting an extensive array of HTTP methods and headers: this provides developers with a cleaner, concise method for making asynchronous requests. Contemporary JavaScript applications often prefer it for its clarity and ease of use.
Example
<!DOCTYPE html> <html> <body> <h1>Fetch API Example</h1> <button onclick="fetchApi()">Make Request</button> <pre id="result"></pre> <script> function fetchApi() { fetch('https://jsonplaceholder.typicode.com/users/3') .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .then(data => { var formattedData = JSON.stringify(data, null, 2); document.getElementById('result').innerText = 'Fetch API:\n' + formattedData; }) .catch(error => { document.getElementById('result').innerText = 'Fetch API Error: ' + error.message; }); } </script> </body> </html>
Using Axios
Designed for making HTTP requests, Axios emerges as a popular JavaScript library. Its popularity is largely due to its clean and concise syntax: built on Promises; furthermore, it boasts automatic JSON data transformation support features that set it apart from other libraries in the field. Offering more than just basic functionality, Axios presents advanced features such as request and response interceptors, a robust selection for managing AJAX operations within the context of modern web development environment.
Example
<!DOCTYPE html> <html> <head> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> </head> <body> <h1>Axios Example</h1> <button onclick="axiosExample()">Make Request</button> <pre id="result3"></pre> <script> function axiosExample() { axios.get('https://jsonplaceholder.typicode.com/users/5') .then(response => { var formattedData = JSON.stringify(response.data, null, 2); document.getElementById('result3').innerText = 'Axios:\n' + formattedData; }) .catch(error => { document.getElementById('result3').innerText = 'Axios Error: ' + error.message; }); } </script> </body> </html>
Using Ajax jQuery
The $.ajax method in jQuery simplifies the AJAX request process: a popular approach previously; however, its usage has waned alongside modern JavaScript's ascent. Offering an interface that is both consistent and cross-browser compatible, jQuery Ajax remains suitable for projects already using or needing specific features of jQuery due to these advantages it presents. However, for new projects, modern alternatives may be preferred.
Example
<!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> </head> <body> <h1>jQuery Ajax Example</h1> <button onclick="jqueryAjax()">Make Request</button> <pre id="result4"></pre> <script> function jqueryAjax() { $.ajax({ url: 'https://jsonplaceholder.typicode.com/users/7', method: 'GET', dataType: 'json', success: function (data) { var formattedData = JSON.stringify(data, null, 2); document.getElementById('result4').innerText = 'jQuery Ajax:\n' + formattedData; }, error: function (xhr, status, error) { document.getElementById('result4').innerText = 'jQuery Ajax Error: ' + error; } }); } </script> </body> </html>
Ajax Use Cases
In real-world scenarios, developers commonly employ Ajax to create web applications that are both responsive and interactive. A pertinent example: a social media platform; here, users have the ability - thanks to Ajax, to add or load new comments in the background without needing an entire page refresh. Dynamic updating ensures a user experience that is smooth and uninterrupted, permitting individuals to engage with content and one another seamlessly. This process yields a platform more responsive and engaging; it amplifies user interaction thus enhancing satisfaction.
Prominent companies utilizing Ajax for enhanced user experiences include Google (Gmail, Maps), Facebook, Twitter, Amazon, Netflix, GitHub, LinkedIn, YouTube, Microsoft Office Online, and Uber. Ajax is employed for real-time updates, dynamic content loading, and seamless interactions on their respective platforms.