⇧
vadnica-logo
Editor My Blog Password Manager Finance My Services About the Project Telegram O meni O meni

JavaScript AJAX

JavaScript AJAX (Asynchronous JavaScript and XML) is a powerful technique that allows the creation of dynamic and responsive web applications. With its help, we can retrieve data from a server and update parts of a web page in the background without interrupting the user by reloading the entire page.

EXAMPLE
RESULT

What is AJAX?

It is important to understand that AJAX is not a programming language, but rather a combination of existing technologies:

  1. The XMLHttpRequest object – built into the browser, it handles requesting data from a server.
  2. JavaScript and the HTML DOM – they handle displaying the received data on the page.

How Does AJAX Work in Practice?

The name AJAX is slightly misleading today because, in addition to XML, we very often transfer data as plain text or in the modern JSON format. The entire process of how AJAX works takes place in the following steps:

  1. The user triggers an event (e.g., clicking a button or entering text).
  2. JavaScript creates an XMLHttpRequest object.
  3. The object sends a request to the web server.
  4. The server processes the request and prepares a response.
  5. The server sends the response back to the browser.
  6. JavaScript reads the response and updates the content on the screen.

JavaScript AJAX – Quick Reference (Cheat Sheet)

AJAX (Asynchronous JavaScript and XML) allows web pages to exchange data asynchronously with a server in the background. The table below provides a quick and transparent guide to all the key steps, states, and methods of the XMLHttpRequest object that you use in your projects.

Concept / Method Description Syntax / Value Practical Use Case Example
1. Object Initialization
new XMLHttpRequest() Creates a new instance of the object, which is the baseline for the entire AJAX communication. const xhttp = new XMLHttpRequest(); ▶ Code Example
2. Preparing and Submitting the Request
open() Prepares the request. Specifies the method (GET/POST), the file path, and whether it is asynchronous (true/false). xhttp.open("METHOD", "URL", async) ▶ Code Example
send() Actually sends the request to the server. For the POST method, we pass the data inside the parentheses. xhttp.send(data) ▶ Code Example
setRequestHeader() Adds an HTTP header to the request. Required when sending data via POST forms. xhttp.setRequestHeader("header", "value") xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
→ State Properties (readyState)
readyState Contains the current state of the request (from 0 to 4). Number 4 means that the transfer is complete. Values: 0 to 4 if (xhttp.readyState === 4) { ... }
• Value 0 UNSENT: The object has been created, but the open() method has not been called yet. 0 Initial state of the object.
• Value 1 OPENED: The open() method has been successfully called. The request is ready. 1 Ready for the send() call.
• Value 2 HEADERS_RECEIVED: The send() method has been called, and the response headers are available. 2 The server has accepted the request.
• Value 3 LOADING: Data transfer is in progress; the response body is downloading. 3 Data is traveling to the browser.
• Value 4 DONE: The operation is completely finished. The data is ready for processing. 4 Standard condition to enter data processing.
→ Server HTTP Statuses (status)
status Returns the numerical HTTP status of the response sent by the server. Status code (e.g., 200, 404) if (xhttp.status === 200) { ... }
• Status 200 OK: The request was successful, and the server returned the requested data. 200 Everything is fine, we can print out the data.
• Status 403 Forbidden: Access to the file on the server is denied. 403 Permission error on the server side.
• Status 404 Not Found: The requested file or PHP script does not exist on the server. 404 Incorrect path or filename in the open() method.
• Status 500 Internal Server Error: A server error occurred (often a bug in the PHP code). 500 The PHP script crashed before delivering a response.
3. Listening for Events and Reading the Response
onreadystatechange An event that triggers every time the value of the readyState property changes. Event listener (function) xhttp.onreadystatechange = function() { ... };
responseText Contains the server response as a plain text string (String). Text string container.innerHTML = xhttp.responseText;
responseXML Contains the server response as an XML document that can be traversed using DOM methods. XML object const xmlDoc = xhttp.responseXML;
4. Modern Alternative (Modern AJAX Requests)
fetch() Modern replacement for XMLHttpRequest based on Promises. Results in much shorter code. fetch(URL) ▶ Code Example
async / await Keywords that allow us to write asynchronous Fetch code linearly without chaining .then(). async function() { await fetch(); } ▶ Code Example

Practical Implementation Examples

In practice, AJAX requests are most commonly divided into simple reading (GET) and securely sending data for processing (POST):

HTTP Request Type Features and Usage Action
1. Simple Retrieval (GET)
Data is read from a text, JSON, or PHP file. Parameters are sent directly within the URL link.
Fast operation, data is visible in the URL address bar. Ideal for search engines, alphabetic filters, and simple readouts. ▶ Code Example
2. Database Communication (SQL)
JavaScript sends a parameter to a PHP script, which runs a MySQLi query and returns the exact data back to the browser.
Dynamic display of customers, items, or transaction history without refreshing the entire interface. ▶ Code Example