AJAX - AJAX with Web Storage for Temporary Client-Side Data
AJAX with Web Storage refers to the use of browser storage mechanisms, mainly localStorage and sessionStorage, together with AJAX requests. AJAX allows a web application to communicate with a server and retrieve or send data without reloading the entire webpage. Web Storage allows the browser to temporarily or persistently store small amounts of data on the user's device. Combining these technologies can reduce unnecessary server requests and make web applications faster and more responsive.
1. Understanding Web Storage
Web Storage is a browser feature that provides a simple way to store data as key-value pairs. It has two main types: localStorage and sessionStorage.
localStorage keeps data in the browser even after the browser window or tab is closed. The data remains available until it is explicitly removed by the application or the user.
sessionStorage stores data only for the lifetime of a particular browser tab or window. When that tab or window is closed, its stored data is normally removed.
Both storage mechanisms use a similar JavaScript API.
localStorage.setItem("username", "Rahul");
let username = localStorage.getItem("username");
console.log(username);
For session storage, the syntax is similar:
sessionStorage.setItem("page", "dashboard");
let page = sessionStorage.getItem("page");
console.log(page);
2. Using AJAX to Retrieve Data
An AJAX request can obtain information from a server without refreshing the webpage. For example, a website might request a list of products from a server.
let xhr = new XMLHttpRequest();
xhr.open("GET", "products.json", true);
xhr.onload = function () {
if (xhr.status === 200) {
let products = JSON.parse(xhr.responseText);
console.log(products);
}
};
xhr.send();
When the server responds, the application can process the returned data and display it on the page.
However, if the same information is requested repeatedly, the browser may have to communicate with the server every time. Web Storage can be used to retain suitable data locally and reuse it when appropriate.
3. Storing AJAX Responses
Suppose an AJAX request retrieves user preferences or a list of categories that does not change frequently. The application can store the response in localStorage.
let xhr = new XMLHttpRequest();
xhr.open("GET", "categories.json", true);
xhr.onload = function () {
if (xhr.status === 200) {
localStorage.setItem("categories", xhr.responseText);
let categories = JSON.parse(xhr.responseText);
console.log(categories);
}
};
xhr.send();
The response is converted into a string and stored under the key categories. The application can later retrieve this information without immediately making another AJAX request.
let storedCategories = localStorage.getItem("categories");
if (storedCategories) {
let categories = JSON.parse(storedCategories);
console.log(categories);
}
This approach is particularly useful for relatively stable information.
4. Checking Storage Before Making an AJAX Request
One useful pattern is to check whether suitable data already exists in Web Storage before contacting the server.
let storedData = localStorage.getItem("categories");
if (storedData) {
let categories = JSON.parse(storedData);
console.log(categories);
} else {
let xhr = new XMLHttpRequest();
xhr.open("GET", "categories.json", true);
xhr.onload = function () {
if (xhr.status === 200) {
localStorage.setItem("categories", xhr.responseText);
let categories = JSON.parse(xhr.responseText);
console.log(categories);
}
};
xhr.send();
}
In this example, the application first looks for previously stored data. If the data is available, it can use that information directly. If it is unavailable, an AJAX request is sent to the server.
This can reduce unnecessary network communication and improve the perceived speed of the application.
5. Using sessionStorage with AJAX
sessionStorage is useful when information is required only during the current browsing session.
For example, a multi-step form may retrieve information through AJAX and temporarily store the user's progress.
sessionStorage.setItem("selectedCourse", "JavaScript");
The stored value can then be retrieved later:
let course = sessionStorage.getItem("selectedCourse");
console.log(course);
This is useful for temporary information such as selected filters, current form progress, temporary interface preferences, or information needed while navigating between pages during the same session.
6. Storing JSON Data
AJAX applications frequently receive JSON from web servers. Web Storage, however, stores values as strings. Therefore, JavaScript objects and arrays must be converted into strings before they are stored.
JSON.stringify() can be used for this purpose.
let user = {
name: "Anita",
age: 22,
course: "Computer Science"
};
localStorage.setItem("user", JSON.stringify(user));
When the data is retrieved, JSON.parse() can convert the string back into a JavaScript object.
let storedUser = localStorage.getItem("user");
let user = JSON.parse(storedUser);
console.log(user.name);
This technique is commonly used when AJAX responses contain structured information.
7. Updating Stored Data After an AJAX Request
Stored information should not always remain unchanged. If an AJAX request retrieves updated information from the server, the application can replace the old stored value with the new response.
let xhr = new XMLHttpRequest();
xhr.open("GET", "profile.json", true);
xhr.onload = function () {
if (xhr.status === 200) {
localStorage.setItem("profile", xhr.responseText);
let profile = JSON.parse(xhr.responseText);
console.log(profile);
}
};
xhr.send();
Here, every successful response updates the locally stored profile information. This allows the application to maintain a more recent copy of the data.
8. Removing Stored Data
Applications should also be able to remove information that is no longer required.
To remove one item:
localStorage.removeItem("categories");
To clear all data stored by the current website:
localStorage.clear();
For session storage, the same methods can be used:
sessionStorage.removeItem("selectedCourse");
Removing outdated or unnecessary information helps prevent storage from becoming cluttered.
9. Advantages of Combining AJAX and Web Storage
The combination of AJAX and Web Storage provides several benefits.
First, it can reduce the number of repeated requests sent to the server. If suitable information is already stored locally, the application can reuse it.
Second, it can improve responsiveness. Reading information from browser storage is generally faster than waiting for a network request to complete.
Third, it can improve the user experience by allowing frequently used non-sensitive information to remain available during navigation.
Fourth, it can reduce network usage because the application does not need to download identical information repeatedly.
10. Important Limitations and Security Considerations
Web Storage should not be treated as a replacement for a server-side database. It is intended for relatively small amounts of client-side data, and storage limits vary by browser.
Sensitive information such as passwords, authentication tokens, financial information, or confidential personal data should generally not be placed in Web Storage because JavaScript running on the page can access it.
Another important issue is stale data. Information stored in localStorage may become outdated if the server changes the corresponding data. Applications therefore need an appropriate strategy for deciding when stored data should be refreshed.
Web Storage is also specific to the browser and origin. Data stored by one website is not normally accessible to another website.
Conclusion
AJAX with Web Storage combines asynchronous server communication with browser-side data storage. AJAX can retrieve current information from a server, while localStorage or sessionStorage can retain suitable information for later use. A common approach is to check Web Storage first, use the stored data when it is appropriate, and make an AJAX request when the information is missing or needs to be refreshed. This can reduce unnecessary network requests and improve application responsiveness, while careful handling of data freshness, storage limits, and security is essential.