Tips for avoiding redundant AJAX requests

Currently, I am working with JavaScript and not jQuery.

Imagine a scenario where I have 3 users in my database [Kim, Ted, Box] and 3 buttons structured as follows:

<button class="user">Kim</button>
<button class="user">Ted</button>
<button class="user">Box</button>
<div id="displayArea"></div>

Whenever a user clicks on any of the buttons, it should display the respective user information within the div element.

For instance, if I click on the Kim button, an ajax call retrieves and displays Kim's information. Then, upon clicking Ted, another ajax call fetches Ted's data. However, if I click on Kim again afterward, I want to avoid making a new ajax call and instead retrieve the data from cache or another source if it was already loaded previously. How can this functionality be implemented?

The reason behind this requirement is to enhance user experience by eliminating unnecessary loading times for data that has been fetched before.

Answer №1

To enhance the efficiency of data retrieval, introduce a new layer of abstraction by developing a function that manages caching and is responsible for either fetching the data from cache or executing an Ajax request to obtain it. Here's an example:

var getDataForUser = (function() {
    /**
     * An object is utilized as a cache with user names serving as keys.
     * This variable remains inaccessible outside this function
     */
    var cache = {}; 

    /**
     * The core function for data retrieval
     */
    return function getDataForUser(user, callback) {
        if (cache.hasOwnProperty(user)) { // handling cache hits
            callback(cache[user]);
        } else {
            // construct the URL incorporating the user name
            var url = ...;
            makeAjaxRequest(url, function(data) { // addressing cache misses
                cache[user] = data; // store in cache
                callback(data);
            });
        }
     };
}());

Subsequently, initiate the call

getDataForUser('John', function(data) { /*...*/ });

twice which will result in accessing the cached data upon repeating the process.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why does the <select> dropdown flash when I select it?

Currently utilizing Angular 1.3 and Bootstrap 3.3.x CSS without the JS functionality. There is also an interesting animated GIF embedded within. <div class="form-group"> <div class="col-lg-3"> <label clas ...

What is the best way to insert a new row into a table upon clicking a button with Javascript?

Hi everyone, I'm facing an issue with my code. Whenever I click on "Add Product", I want a new row with the same fields to be added. However, it's not working as expected when I run the code. Below is the HTML: <table class="table" id="conci ...

How did my attempt to add a length() method to Object end up breaking jQuery?

Here is the code I created: Object.prototype.length = function(){ var count = -1; for(var i in this) count++; return count; } Surprisingly, when viewing my page with Firebug enabled, it gives an error stating that jQuery's .appendTo() is ...

Tutorial on displaying historical pricing data on a chart utilizing props in Vue Chartkick

I recently discovered a chart library called Chartkick for Vue projects. If you're interested, you can check it out here: In my project, I have data passed as props to a component. However, I encountered an issue where the prop couldn't be acces ...

Extracting Raw Body from Stripe Webhook in NextJS

I'm feeling frustrated trying to get a raw body passed for the Stripe webhook in NextJS! Despite trying numerous solutions from various sources, I just can't seem to get it to work. Calling upon the developers with special powers (of which I am ...

When integrating react-hook-form with Material-UI TextField in a form, an error occurs stating that "TypeError: e.target is undefined" when

Hey there, I stumbled upon something fascinating and could really use some assistance. Every time I attempt to perform an onChange, I run into the following error: TypeError: e.target is undefined. Here's a snippet of my setup: import React, { useE ...

Exploring each list item within the specified unordered list

Here is a basic code snippet: var ulreq = $("#abc").children("ul.ghi"); var lists = ulreq.find("li"); for( var i = 0; i < lists.length; ++i){ alert(lists[i].text()); // Display the values in these li }<script src="https://ajax.googleapis.com/ajax ...

The process of uploading a file through ajax results in it being sent to php://input

---Resolved By making the following adjustment: var request = new XMLHttpRequest(); request.open("POST", $(this).attr('action')); request.send(formData); The issue is now fixed, but I am unsure of the underlying reason. I have not found an exp ...

Exploring the features of NextJS version 13 with the benefits

Starting from the 13th step, SSR is utilized by default and in order to opt for client side rendering you must specify it at the top like so: 'use client' Currently, my setup involves TypeScript and styled-component integration. Take a look at ...

Backend framework

Currently, I am in the process of developing a robust web application that heavily relies on JavaScript and jQuery, with ajax functionality included. Additionally, there will be a database in place, managed using mySQL with several tables. I'm undeci ...

@vue/cli for automated unit testing

I'm currently using @vue/cli version 4.5.15 and looking to write tests for my components. However, when I run the command, yarn test:unit I encounter an error that says: ERROR command "test:unit" does not exist. Do I need to perform additional se ...

How to access form elements within a submit function without specifically defining the form name

I have a form that I am submitting using a submit function. However, instead of using document id for submission variable, I am utilizing classes. $(".modalform").submit(function(event) { /* prevent form from submitting normally */ event.preventDefa ...

Sharing a Twitter thread using Twit library with Node.js

I have been using Node.js along with the npm Twit module to post tweets on Twitter, and while it works for a single tweet, I am facing issues when trying to post multiple tweets as a thread. When attempting to post a series of tweets together, they do not ...

Is combining Laravel Blade and Vue to render AJAX data a good idea?

I am trying to implement AJAX rendering of news using Blade and Vue. <div id="news"> <div class="l_news"> <div class="post" v-for="post in posts"> <div class="image" style="background: url({{ asset('images ...

Creating three functions with the same name, one with a callback, another with a promise, and the third with async/await, can

I am looking to create a versatile function that can be used in 3 different ways to handle npm dependencies Using Promises Using callbacks Using async/await For Instance 1) Using async/await var mongoose = require('mongoose'); async fu ...

Utilizing AJAX and PHP to refresh information in the database

For my project, I need to change the data in my database's tinyint column to 1 if a checkbox is selected and 0 if it is deselected. This is the Javascript/Ajax code I have written: <script> function updateDatabaseWithCheckboxValue(chk,address) ...

What is the method for breaking down a React useState hook into separate variables within a namespace?

Personally, I like to group React props into namespaces for better organization. When using the useState hook, I follow this approach. function MyComponent() { const [todoCount, setTodoCount] = useState(100); const [doneCount, setDoneCount] = useSta ...

Encountering a Node Js post handling error with the message "Cannot GET /url

This is my ejs file titled Post_handling.ejs: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>POST-Handling Page</title> </head> <body& ...

What could be the reason for StaticComponent constantly re-rendering despite having a static state that does not change

I'm trying to grasp the core concepts of how React triggers component re-rendering upon state changes. In the scenario described below, the console.log('hi') statement within the StaticComponent is executed every time the onChange event han ...

Creating a JSX syntax for a simulated component and ensuring it is fully typed with TypeScript

Looking for some innovative ideas on how to approach this challenge. I have a test helper utils with added types: import { jest } from '@jest/globals' import React from 'react' // https://learn.reactnativeschool.com/courses/781007/lect ...