A new long polling AJAX request is triggered whenever there is a change in the parameter

function AjaxRequest(params, url) {
    if (params) {
        this.params = params;
        this.type = "GET";         
        this.url = url;
//      this.contentType = "multipart/form-data";
        this.contentLength = params.length;;
    }
}

AjaxRequest.prototype.createXmlHttpObject = function() {
    try {
        this.xmlHttp = new XMLHttpRequest();
    }
    catch (e) {
        try {
            this.xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
        }
        catch (e) {}
    }

    if (!this.xmlHttp) {
        alert("Error creating XMLHttpRequestObject");
    }
}

AjaxRequest.prototype.process = function() {
    try {
        if (this.xmlHttp) {
            document.getElementById("loading"+this.params).innerHTML = "processing...";
            document.getElementById("loading"+this.params).className = "progressing";
            this.xmlHttp.onreadystatechange = this.handleRequestStateChange();
            this.xmlHttp.open(this.type, this.url, true);
            this.xmlHttp.setRequestHeader("Content-Type", this.contentType);
            this.xmlHttp.setRequestHeader("Content-Length", this.contentLength);
            this.xmlHttp.send(this.params);
            }
        }
        catch (e) {
            document.getElementById("loading"+this.params).innerHTML = "";
            alert("Failed to establish connection with server");
        }
    }

AjaxRequest.prototype.handleRequestStateChange = function() {
    var self = this;
    return function() {
        try {
            if (self.xmlHttp.readyState == 4 && self.xmlHttp.status == 200) {
                self.handleServerResponse(); // calling the method handleServerResponse
            }
        }
        catch (e) {
            alert(self.xmlHttp.statusText);
        } 
    };
}

AjaxRequest.prototype.handleServerResponse = function() {
    try {
        if(this.xmlHttp.responseText.length > 0){
            document.getElementById("loading"+this.params).innerHTML = this.xmlHttp.responseText;
        }
    }
    catch (e) {
        alert("Error reading server response");
    }
}

function CreateAjaxControl(params, url){
    var con = $("#"+params+" select").val();
    url += "?id="+params+"&con="+con;
    var ajaxRequest = new AjaxRequest(params, url);       
    ajaxRequest.createXmlHttpObject();
    ajaxRequest.process();
    ajaxRequest.count = 0;
    ajaxRequest.progress = CheckingProgress;
    ajaxRequest.progress(ajaxRequest, ajaxRequest.params, ajaxRequest.count);
    //var ajaxRequest = new AjaxRequest(params, url);
    //ajaxRequest.checking = setInterval(function(){CheckingProgress(ajaxRequest.params);}, 100);

}

//function Check(id){
//    var res = 0;
//    while( res != "done..."){
//        res = CheckingProgress(id, res);
//    }
}


function CheckingProgress(obj, id, count){
    var self = obj;
    if (window.XMLHttpRequest){
        xmlhttp8 = new XMLHttpRequest();
    }else{
        xmlhttp8 = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp8.onreadystatechange = function(){
        if (xmlhttp8.readyState==4 && xmlhttp8.status==200){
            var result = xmlhttp8.responseText.split(',');
            document.getElementById("loading"+id).innerHTML = result[0] + " out of " + result[1];
            self.count = result[0];
            self.progress(self, self.params, self.count);
        }else if(xmlhttp8.status==404){
            document.getElementById("loading"+id).innerHTML = "done...";
            //return "done";
        }
    }
    xmlhttp8.open("GET","views/test2.php?id="+id+"&count="+count,true);
    xmlhttp8.send();
}

I have implemented a long polling script that continuously fetches the number of updated records from my database. Though it functions correctly when there are no updates, it encounters an issue when I update a record in the database - a new ajax request is created with the updated count as a parameter while the original request remains unchanged. What could be causing this problem? Is it related to how I assigned my long polling method to an object? Any insights would be greatly appreciated.

Answer №1

Why does the CheckingProgress() function include a parameter count? It seems redundant since obj.count is always equal to the count parameter passed in each time the function is called. Instead of referencing count at the end of the function, it could simply be replaced with self.count.

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

How to locate the position of an element within a multi-dimensional array using TypeScript

My data structure is an array that looks like this: const myArray: number[][] = [[1,2,3],[4,5,6]] I am trying to find the index of a specific element within this multidimensional array. Typically with a 1D array, I would use [1,2,3].indexOf(1) which would ...

Adjusting the range input alters color progressively

I am trying to create a range input with a dynamic background color that changes as the slider is moved. Currently, the background is blue but I want it to start as red and transition to yellow and then green as the slider moves to the right. Does anyone ...

Tips for showing an image during an asynchronous postback

I've implemented an Ajaxable application with UpdateProgress for each postBack event, and it's all working perfectly. Now, I'm looking to add another Indicator in my SiteMapPath bar to show that a postback is taking place at any given time. ...

What steps can I take to ensure that my popup images continue to appear?

Currently, I am working on creating a webpage that features thumbnails sourced from a local geoserver. The goal is to have these thumbnails expand into dialog windows that can be moved around. While I have successfully implemented the functionality to expa ...

Tips for uploading a file with fetch

While I know this question has been asked before, none of the solutions seem to be working for me. Initially, I attempted to resolve the issue using axios, but it appears that there is a bug preventing me from utilizing it for file uploads. Therefore, I am ...

Is there a method in JavaScript/jQuery to gently push or flick the scroll so that it can be easily interrupted by the user? Further details are provided below

I am looking for a solution in javascript that will allow the page to automatically scroll down slightly, but I also want the user to be able to interrupt this scroll. When using jquery for auto-scrolling, if the user begins manual scrolling while the ani ...

Having trouble getting two different filters to work properly when filtering data in AngularJs

I have created a plunkr to demonstrate my current situation: The user is required to type a word into the textbox, and upon clicking the button, an angular service retrieves data from a DB based on the input text. The retrieved data is then displayed in a ...

Unraveling the complexities of parsing multi-tiered JSON structures

I am struggling with indexing values from a multi-level JSON array. Here is the JSON data in question: { "items": [ { "snippet": { "title": "YouTube Developers Live: Embedded Web Player Customization" } ...

Is there a way to prompt the native browser message for HTML5 form validation on a custom element?

https://i.sstatic.net/3wuWh.png Can the native validation UI be activated on non-default input elements like divs or similar? I want to develop a custom React element with validation without relying on hidden or invisible input fields. ...

Setting the class attribute dynamically using code behind

Below is a snippet of code I am working with: div1.Attributes.Add("class", "displayNone"); It functions properly during page load but fails to do so during an OnClick event. The issue arises from the fact that my HTML element <div id="div1"></d ...

Why is it that I am unable to utilize the post data stored in $var within my PHP document when making an Ajax call?

Hey there! I've got this function that makes an ajax call. But, for some reason, the $value I'm passing isn't defined in my showuser.php file. Can you help me figure out why? function showUser2(value) { var xhr = new XMLHttp ...

Is there a way to prevent users from selecting certain days in ion-datetime?

After searching through the official documentation, I couldn't find a solution. I am in need of a function similar to the jQuery datepicker beforeshowday function. My goal is to disable all weekends (Saturday and Sunday) in upcoming dates so that user ...

What is the process of replacing fetch with JavaScript?

Looking to test my React application and mock the backend calls, I made the decision to swap out fetch with a Jest function that returns a static value. The issue I encountered was my inability to override the default fetch behavior. After some research, ...

Trouble with Updating Div Content?

Within my HTML code, I have included this JavaScript snippet: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script> <script> var auto_refresh = setInterval( function() { $('#loaddiv').fadeOut ...

Tips for troubleshooting getStaticProps (and getStaticPaths) in Next.js

Currently, I am attempting to troubleshoot the getStaticProps() function within a React component that is being utilized from my pages by implementing console.log() like so: export default class Nav extends React.Component { render() { return & ...

Having a solid grasp of React and Material UI, as well as familiarity with the concept of props and

For my react application, I utilize Material UI (@mui/material). However, I've come to realize that there might be some nuances in how the components interact with each other. For instance, if I nest a MenuItem inside a Box or a Link inside a Typograp ...

Developing Authorization in AngularJS

Incorporating authorization into an AngularJS project is crucial. In my current project, which revolves around a social media concept, users with different roles may have varied access to view files. For instance, envision two distinct roles: customer and ...

What is the best way to verify that a check should have various attributes using chai-things?

Searching for a way to verify if an array in my mocha tests consists of an Object in my Node.js application, I discovered that with Chai-Things, I can use: [{ pet: 'cat' }, { pet: 'dog' }].should.include({ pet: 'cat' }) or ...

Mobile website scroll assistant

Seeking a solution to aid mobile users in scrolling through a lengthy article page. Typically in mobile apps, an alphabetical index assists users in navigating long lists. How can I incorporate a similar feature into a webapp? For context, my tech stack i ...

What is the reason behind the lag caused by setTimeout() in my application, while RxJS timer().subscribe(...) does not have the same

I am currently working on a component that "lazy loads" some comments every 100ms. However, I noticed that when I use setTimeout for this task, the performance of my application suffers significantly. Here is a snippet from the component: <div *ngFor ...