Managing Numerous Ajax Calls

Dealing with Multiple Ajax Requests

I have implemented several Like Buttons on a single PHP Page, which trigger the same Ajax function when clicked to update the corresponding text from Like to Unlike.

The current code works well for individual Like Button clicks, but if I click more than one at the same time and wait for them to update, only the last clicked button changes its text to Unlike.

Can someone suggest a better solution or provide an improved code snippet to address this issue?

Thanks


Page: Like.php

<span id="like1" onclick="ajaxFun(1)">Like</span><br />
<span id="like2" onclick="ajaxFun(2)">Like</span><br />
<span id="like3" onclick="ajaxFun(3)">Like</span><br />
<span id="like4" onclick="ajaxFun(4)">Like</span><br />
<span id="like5" onclick="ajaxFun(5)">Like</span><br />
....
<span id="like10" onclick="ajaxFun(10)">Like</span><br />

Page: ajaxx.js

function ajaxFun(id) {
    document.getElementById("like"+id).innerHTML="Please wait...";
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else {
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            var getData=xmlhttp.responseText;
            if(getData=="ok") {
                document.getElementById("like"+id).innerHTML="Unlike";
            }
            else {
                    document.getElementById("like"+id).innerHTML="Like";
            }
        }
    }
    xmlhttp.open("GET","verify.php?id="+id,true);
    xmlhttp.send();
}

Page : verify.php

This page verifies something and returns "ok" if successful, otherwise "not ok".


Error :(

Like
Like
Like
Please wait...
Please wait...
Please wait...
Please wait...
Please wait...
Please wait...
Unlike

Answer №1

To begin, establish an array specifically for managing AJAX handlers...


var ajaxHandlers = [];
function handleAjax(id) {
    document.getElementById("like"+id).innerHTML = "please wait...";
    
    if (ajaxHandlers["like"+id] == null) {
        if (window.XMLHttpRequest) {
            // code for modern browsers
            ajaxHandlers["like"+id] = new XMLHttpRequest();
        } else {
            // code for old IE versions
            ajaxHandlers["like"+id] = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    
    ajaxHandlers["like"+id].onreadystatechange = function() {
        if (ajaxHandlers["like"+id].readyState == 4 && ajaxHandlers["like"+id].status == 200) {
            var response = ajaxHandlers["like"+id].responseText;
            
            if (response === "ok") {
                document.getElementById("like"+id).innerHTML = "Unlike";
            } else {
                document.getElementById("like"+id).innerHTML = "Like";
            }
        }
    };
    
    ajaxHandlers["like"+id].open("GET", "verify.php?id=" + id, true);
    ajaxHandlers["like"+id].send();
}

Answer №2

My observation is that the use of xmlhttp in a global context may lead to potential issues. To address this, it is recommended to declare it within the function scope to avoid conflicts. For more information, refer to this question and answer.

function ajaxFun(id) 
{
    document.getElementById("like" + id).innerHTML = "wait !!!";
    var xmlhttp = null; /* NEW LINE */
    if (window.XMLHttpRequest)
    {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else
    {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (xmlhttp !== null)
    {
        xmlhttp.onreadystatechange = function()
        {
            if (xmlhttp.readyState == 4)
            {
                if (xmlhttp.status == 200)
                {
                    var getData = xmlhttp.responseText;
                    if (getData == "ok")
                    {
                        document.getElementById("like" + id).innerHTML = "Unlike";
                    }
                    else
                    {
                        document.getElementById("like" + id).innerHTML = "Like";
                    }
                }
            }
        }
        xmlhttp.open("GET", "verify.php?id=" + id, true);
        xmlhttp.send();
    }
    else
    {
        document.getElementById("like" + id).innerHTML = "Could not get XMLHttpRequest";
    }
}

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

Combining Context and MUI's theme provider for effective nesting: A step-by-step guide

Currently, I have a state set up to toggle between dark and light mode on a website that contains numerous nested components. The root App.js file looks like this: function App() { return ( <DarkModeProvider> ...

When using AngularJS services to pass data, the data may be lost when the page is refreshed

I'm facing an issue with transferring data from controller A to controller B using a Factory (or a Service) when the user refreshes the browser. I am able to successfully set the data in controller A and retrieve it in controller B, but upon refreshin ...

JavaScript popup is no more visible on the webpage

Recently, I implemented a pop-up on my website that used cookies to prevent it from appearing every time a user visited a page. However, after making this change, the pop-up stopped showing altogether. Despite my best efforts in testing, researching, and s ...

How to use the var keyword in JavaScript to declare block-scoped variables

At this moment, my goal is to establish a block-scoped variable in JavaScript by utilizing the var keyword. I prefer not to utilize the let keyword due to compatibility issues with certain browsers in ecma6. Is there an optimal and universal method to ac ...

Dealing with Challenges in Constructing JQuery URLs

I'm facing an issue with loading a website into a specific div (div.content). The website I'm trying to load requires a login through a POST request. When the javascript attempts to load the site, it recognizes the redirection to the login form ...

Intercepting the K-pager navigation with a pop-up modal for user confirmation before switching to a different page

Scenario Currently, I have developed a WebApp using kendo, bootstrap, and backbone. One of the key features is a grid that showcases data pulled from a database. This grid has a data source binding with serverPaging enabled. Data Source Configuration al ...

How can I efficiently iterate through the array of index IDs and then iterate individually through the communes, categories, and locations?

Currently, I am developing a nodejs typescript API where I am retrieving an array of objects using a map loop. The data for "communes", "category", and "location" is fetched from another API function based on the issuerId. However, I am facing issues with ...

Error with object props in React using Typescript

Here's a scenario; I have a list of 'Reviews' that I am trying to render. The Proptype for these reviews is as follows: export interface Props { title: string; name: string; reviewdesc: string; rating: number; } In the pare ...

In Node.js Express, the download window won't pop up unless the entire file has been sent in the header response

I have been using Express to develop an API that allows users to download PDF files. The download process is functioning correctly, but I am facing an issue where the download window, which prompts me to select a destination folder for the download, only a ...

I am encountering an issue with running my Mocha tests. Can anyone provide assistance on how to solve this problem?

https://i.sstatic.net/kLnxs.png Could the issue be with the package.json file or am I not executing the proper command to run it? ...

Hiding and showing div elements using CSS, JavaScript, and PHP

Here is the current code snippet: <? while ($row1 = mysql_fetch_object($result1)) { echo '<a href="#" onclick="showhide("'.$row1->id.'");">Name</a>'; while ($row2 = mysql_fetch_object($result2)) { ...

What is the best way to insert a chart into a div using *ngIf in Angular?

I just started using chart.js and successfully created the desired chart. However, when attempting to implement two tab buttons - one for displaying tables and the other for showing the chart - using *ngIf command, I encountered an error: Chart.js:9369 F ...

Tips for displaying an input element across multiple cells in ObservableHQ

Imagine you have the code snippet below representing a checkbox element in Observablehq: viewof myFilter = checkbox({ title: "Foo", description: "bar", options: myOptions, }) How can I display this element multiple times in different cells through ...

The res.download() function is not functioning properly when called from within a function, yet it works perfectly when directly called through the API in a browser

I have a button that, when clicked, triggers the downloadFile function which contacts the backend to download a file. async downloadFile(name) { await this.$axios.$get(process.env.API_LINK + '/api/files/' + name) }, app.get('/api/files/ ...

Prevent draggable canvas elements from overlapping using jQuery

I'm currently working on a project where I need to make three canvas elements draggable while preventing them from overlapping each other. After researching similar issues, I came across the "jquery-ui-draggable-collision" library. Here is the code I ...

Styling the sub-elements using CSS in JavaScript

Currently, I am dealing with two CSS classes: .dragbox and .removebutton. The .dragbox represents a div, while the .removebutton is a button nested within the div. On my page, there are multiple dynamically generated instances of .dragbox. I am seeking ...

Can one retrieve a catalog of Windows Updates that have been installed by utilizing node.js?

Currently, I am working on a JavaScript/Node.js project where I am seeking to retrieve a comprehensive list of all installed windows updates, similar to how it is done using the C# WUAPI 2.0 Type Library. I have attempted utilizing WMI calls (specifically ...

Continuous loop of Vue countdown timer

Hey there! I'm currently working on implementing a countdown timer, but I keep encountering a console error that says 'You may have an infinite update loop in a component render function.' It seems like something needs to be adjusted. expor ...

Why is it that one function does not hold off on execution until Promise.all() is resolved in another function?

I am currently working on a form that allows users to upload files seamlessly. <form @submit.prevent="sendForm" enctype="multipart/form-data"> <input multiple ref="PostFiles" name="PostFiles" type="file" @change="selectFile('add')"> ...

Uncertainty surrounding asynchronous file uploads in Python

Looking to implement asynchronous file uploads for a website that runs on a combination of Python and JavaScript. I've found several informative posts on the topic, but they all recommend different methods, leaving me confused about which one to choos ...