Creating a periodic updater in Prototype.js that will hide elements of a specific class based on the response from an AJAX request

I am currently working on a Periodical Updater using prototype js, and my goal is to hide every element on the page with the class='robot' based on the response received from an AJAX request. If the response matches hidethemall, I want all elements with class='robot' to be hidden. Otherwise, no action should be taken.

Up to this point, I have managed to reset my function after a certain number of periodic updates in order to reduce server load. Here is how my function looks:

function updatePeriodically(span_id, processing_url, parameters,
         frequency, decay, reset_decay_time)
{
    var ajax = new Ajax.PeriodicalUpdater({success: span_id}, processing_url,
    {
        method:'get',
        frequency: frequency,
        decay: decay,
        parameters: parameters,
        evalScripts: true,
        onSuccess: function(response) { //or onComplete
            if (ajax.decay >= reset_decay_time) 
            {
                ajax.decay = decay;
            }
        }
    });
}

updatePeriodically('new_message_count',
    'refresh_unread_messages.php', '&user=currentuser', 10, 2, 1800);

Questions

How can I modify this to prevent updating the div and instead hide every div with the class class='robot' when the AJAX response equals hidethemall?

Answer №1

One issue with the Ajax.PeriodicalUpdater is that it relies on Ajax.Updater, which expects to place the response somewhere, contrary to your needs. To address this, I suggest creating a new custom class.

Ajax.PeriodicalHider = Class.create(Ajax.PeriodicalUpdater, {
    initialize: function($super, selector, url, options) {
        $super(null, url, options);
        // The elements to hide are specified by the selector
        this.selector = selector;
        // Extra time control with max_decay
        this.max_decay = this.options.max_decay;
    },

    onTimerEvent: function() {
        // Utilizing Request instead of Updater
        this.updater = new Ajax.Request(this.url, this.options);
    },

    updateComplete: function($super, response) {
        $super(response);
        if (this.max_decay) {
            // Adjust decay time if necessary
            this.decay = Math.min(this.decay, this.max_decay);
        }
        if (response.responseText == 'hidethemall') {
            // Hide all elements matching the selector
            $$(this.selector).each(Element.hide);
            // Stop further updates as no action needed
            this.stop();
        }
    }
});

new Ajax.PeriodicalHider('.robot', 'messages_compter_non_lus_actualise.php', {
    method: 'get',
    frequency: 10,
    decay: 2,
    max_decay: 1800,
    parameters: '&membre=lesucces'
});

This code has been successfully tested.

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

Tips for inserting an item into the parent window: Chrome-specific (compatible with all other browsers)

In my HTML file, I have an iFrame element like this: <iframe src="frame.html" width="2000" height="1000"></iframe> When trying to use jQuery's append function from within the iFrame to add a DIV to the parent window, it works fine in Fir ...

"Utilizing a function from an external file within the Main App function - a step-by-step guide

I am currently learning React.js and I have come across a challenge that I'm unable to solve easily. I am trying to use functions instead of classes in my code, but I am struggling with using these functions as components within my Main function. Here ...

Display a preview of a React component

Currently facing a challenge where I need to create a form for users to adjust the title, background color, button background, text color, and other settings of a component. I want to provide a live preview of the component as the user makes changes. I en ...

After deploying React with Gatsby, the sequential fade-in animation for the gallery is not functioning as expected

If you want to see the source code, it's available here: Source Code And to view the deployed site, click on this link: Deployed Site The goal I'm aiming for is quite simple and direct. Initially, I used a query to load all the image files fro ...

How can I fix the issue of the onClick function in my React list not activating the toggle?

How to Activate Toggle Functionality Currently, I am working on a project using React where I developed a list with active states. I have implemented the onClick functions, but unfortunately, they are not working as intended. When I click on the list item ...

Aggregation in Kendo Grid specifically for the current page

I'm currently facing an issue with the Kendo Grid aggregate function that I'm struggling to resolve. Within the grid, I have multiple rows with numerical values. My goal is to display the total sum of these rows at the bottom of the grid. The f ...

Getting precise coordinates on a transparent PNG file using JavaScript Canvas

https://i.sstatic.net/Zw8is.png Hey there, I'm a bit puzzled about the getImageData function mentioned on this page. I have an image in png format with a transparent background. My goal is to retrieve the x and y coordinates for both left and right ...

Cross domain requests with jQuery's getJSON function

Struggling to fetch data using jQuery Cross Domain from GitHub, but hitting a roadblock! I've come across suggestions to use jsonp requests, but can't seem to figure out what's going wrong. http://jsfiddle.net/jzjVh/ Chrome seems to be int ...

Execute the PHP file using a script tag

Is there a way to include PHP code within <script>? For example, like this: `<script src="example.php">. I understand that the script tag is typically used for JavaScript, but I want PHP to generate JS that can be inserted using the s ...

Guide on sending the boolean result returned from controller to view in Spring MVC

I need to pass the boolean value returned by my controller method to the view, where I can display an alert message based on this flag. Here is my controller code: @RequestMapping(value = "/testing", method = RequestMethod.POST) public Boolean testing(@Re ...

I am struggling to retrieve a value from the angular.forEach function, the flag value is not being obtained. What could be

I'm having an issue with my controller.js file. I can't seem to access the value from the angular.forEach function, specifically the flagvalue isn't being retrieved. Is it because the scope of flagvalue ends when the forEach function complet ...

Express and Webpack Error: "SyntaxError: Unexpected token <"

I am facing difficulties while testing my React webpage that I built using Webpack. When trying to run an Express server, the localhost page appears blank with a console message saying Uncaught SyntaxError: Unexpected token <. It seems like the webpage ...

Generating ChartJS in Real-time

I have a straightforward form where the user selects a start date and an end date. Once these dates are selected, the tool automatically fetches data from a website in JSON format. Below is the code for my Angular controller: (function () { angular.m ...

Is there a way to dynamically assign ng-include or ng-controller in Angular JS?

I'm a beginner with Angular JS and after some research, it seems like what I want to achieve might not be possible. However, I'd like to explore if there is an alternative solution that can provide a similar outcome. My goal is to populate a pag ...

"Troubleshooting issues with the functionality of AngularJS - Bootstrap Material Datetimepicker

I recently implemented a datetimepicker from this datetimepicker library into my AngularJS project. I have included jQuery, Moment, and the datetimepicker in the head tag. The input field is nested within an ng-repeat, and I have initialized the datetimepi ...

A step-by-step guide on extracting JSON data from PHP and presenting it in a formatted list

I am working on a simple jQuery AJAX form submission. When the form is submitted, my PHP script echoes json_decode($result). Below is my AJAX script: <script> $("#ajaxquery").live( "submit" , function(){ // Intercept the for ...

Is it possible to access the Zustand store from outside a functional component?

Within my util.ts file, I have defined a function that can be utilized in various places. This function accesses both a variable and a function from the Zustand store. import useStore from "@/store/useStore"; const { roomState, setRoomState } = ...

Is there a way to transform a large gltf file into jsx format?

I recently created a 3D scene in Blender and wanted to incorporate it into my React Three Fiber project. However, after exporting the scene to glTF format, I discovered that the file contained around 300k lines. The strange thing is that the file works per ...

What is the method to modify an action in an Ajax function?

I am trying to modify the action in the AjaxUpload function. The issue is that the value of setnamefile in the action does not change because the page does not reload. My idea was to change the action on submit, but I have not been able to do so successfu ...

How to eliminate a line in an XML file with PHP

I have been struggling with a seemingly simple task and tried various methods to no avail. I now find myself seeking guidance on how to achieve my goal. My Objective: I am looking to remove a specific element from an XML file. The Current Situation: The ...