Execute an AJAX function to monitor a JSON response at intervals of 3 seconds

I'm looking to verify if my user has been updated from another system using JavaScript.

Can anyone assist me in creating a function that can analyze a JSON response and determine if it is true or false?

The URL /user/updatecheck/ provides a JSON response in the format: {"updated": "true"} or {"updated": "false"}

<script type="text/javascript>

$(document).ready(function() {
    var updated='2013-01-02T10:30:00.000123+02:00'; // user variable from the system, will be empty if the user is not updated       

    if (!updated) {
        $('#not-updated').modal('show');

        var updatedCheck = window.setInterval(    
            $.ajax({
                url: "/user/updatecheck/", // Returns {"updated": "true"} or {"updated": "false"}
                data: dataString,
                dataType: "json", 
                success: function(data){ 

                    if (json.updated == 'true') { // unsure about this method
                        window.clearInterval(updatedCheck);
                        // The user has been updated - page needs to be reloaded
                    }
                } // success

            })
        , 3000);  // Hoping this is the function to check the URL every 3 seconds until it returns true
    }

}); 
$(document).ajaxStop(function(){
    window.location.reload();
});

</script>

This code doesn't seem to be functioning as expected. I am uncertain if my AJAX function is correct, as I only see the modal window when the user is not updated initially, and the page does not reload when the URL /user/updatecheck/ returns true.

Answer №1

It seems that the way you are incorporating the jQuery ajax function within the setInterval is not correct. I recommend placing it inside a separate function for better organization and functionality.

var updatedCheck = window.setInterval(    
        function(){$.ajax({
                    url: "/user/updatecheck/", //This will return either {"updated": "true"} or {"updated": "false"}
                    data: dataString,
                    dataType: "json", 
                    success: function(data){ 

                        if (data.updated == 'true') { //Ensure to refer to data instead of json
                            window.clearInterval(updatedCheck);
                               //User has been updated - reload page as necessary
                        }
                    } //success

                })}
        , 3000);

The response data from the ajax request should be accessed through the 'data' parameter in your success callback function. You can log the data result to the console using console.log(data);, or display it with an alert using alert(data);. Make sure to use 'data.updated' to access the relevant information. It's important to verify whether the 'json' variable used in the if condition has been properly initialized.

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

Is my utilization of the Promise feature correct?

I am currently using node to fetch data from a URL with the help of cheerio. const request=require('request'); const cheerio=require('cheerio'); const Promise = require('promise'); The function getDataParms(parm1, parm2) ret ...

Issue with Angular UI Router arises when state cannot be resolved upon page reload

I'm currently facing an issue with routing that I mentioned in the title. Even though my route is functioning, it encounters difficulties when the page is reloaded. Below is the routes object: { state: 'locations', config: { ...

Delay in changing the z-index of FloatingActionButton on hover

In my current issue, I am facing a problem where a div that is meant to always stay below a FloatingActionButton (FAB) ends up temporarily appearing above it when z-index values are changed. The scenario is such that upon clicking the FAB, an invisible ove ...

Learn how to dynamically import and load components in VueJS while rendering a list

I am currently rendering a list. <div v-for="msg in messages"> <div v-if="msg.type==='component'"> <component v-bind:is="getComponent(msg.component)" :data="msg.data" :text="msg.text"></component> </div> ...

The power of MobX lies in its ability to provide a deep

I'm currently delving into the concept of deep observability in MobX. I'm looking for insights on why the autorun function is not being triggered every time I call setCommentCountForPost in the code snippet below. Can someone point me in the rig ...

execute a function when an image is clicked using jQuery

How can I create an onclick event for the variable imageCatuaba? function setCatuaba(map) { var imageCatuaba = { url: 'images/catuskov.1.png', origin: new google.maps.Point(0, 0), anchor: new google.maps.Point(0, 32) }; I'm ...

Linking a variable in typescript to a translation service

I am attempting to bind a TypeScript variable to the translate service in a similar way as binding in HTML markup, which is functioning correctly. Here's what I have attempted so far: ngOnInit() { this.customTranslateService.get("mainLayout.user ...

What steps can I take to replicate a 'heap limit Allocation failed' error?

Context I encountered a challenging issue where my program displayed a FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory This occurred when the memory usage reached around 512 mb Scavenge (reduce) 507.8 (518.9) -> 507.2 ...

Is it possible to detect inline elements that have been wrapped?

I am facing a challenge with displaying an indefinite amount of in-line elements. Depending on the width of the browser, some elements may shift to a new line. I am curious to know if it is possible to identify and isolate these rows of elements, or if the ...

Implement lazy loading for scripts in Next JS

Currently working on a project with Next JS and focusing on optimizations through Google's Page Speed Insights tool. One major performance issue identified is the presence of 3rd party scripts, specifically the Google Tag script (which includes Google ...

Execute the Selenium function repeatedly using values from an array in a loop

I am facing a challenge with running a selenium script in a loop to populate a database. I have an array of objects consisting of 57 items that need to be processed through the loop asynchronously. My goal is to iterate through each store, check its status ...

Error loading Azure Active Directory web form: Server returned a 401 status code for the requested resource

I recently made changes to my web site (incorporating a web form and entity framework) to use AAD connection, following the guidance in this insightful blog post. However, I am encountering an issue where scripts and css files are not loading properly. Th ...

What is the best way to incorporate a button for toggling CSS animations?

I need help adding a button to toggle the animation on this JSFiddle. I tried adding the code below but can't seem to start and stop the animation. body .a [class^="b"] { width: 200px; height: 142.8571428571px; margin: 0 auto; ...

Using JavaScript to Set Values and Manage Session State in APEX

Trying to utilize JavaScript in Oracle APEX to set the value and session state. See below function that is being called: function updateItemValue(element) { $s('P2020_SELECTED', element); apex.server.process ('MY_PROCESS', { ...

What is the best way to retrieve the value stored in a variable?

In my Node.js program, I have a snippet of code where I am working with a map named `transMap`. My goal is to retrieve the value for 'yy', which should be "ipaddress", and then output it as JSON. While I expected the JSON response to be { "ipaddr ...

Guide on establishing a connection with a TCP server and sending a JavaScript script to it

I am completely new to JS and node. I am using SkyX Pro, a telescope management software that has the capability to run a TCP Server on port 3040. By connecting with Netcat and providing it with Javascript starting with //* Javascript *//, I can control ca ...

Decoding JSON data

How do I parse 2 JSON objects? When AJAX returns just one object, it appears correctly: Object {32 : "Joseph"} However, when it returns more than 2 objects, this is what I get: ResponseText: "{"users":{"32":"Joseph"}}{"users":{"48":"Joseph K."}}" I h ...

Unable to modify the selector to "Remove preview files" on click in PHP and JavaScript

During the process of uploading multiple files (using <input type="file" multiple/>) with preview image file and successfully removing the image preview and file data, I encountered a problem. The issue arises when attempting to change the selector ...

Learn the steps to Toggle Javascript on window resize

Is there a way to toggle Javascript on and off when the window is resized? Currently, resizing the window causes the navigation bar to stick and remain visible above the content. <script> if ( $(window).width() <= 1200 ) { }else{ $('nav& ...

Is there a way to replicate input data from one website onto a totally separate platform?

I am currently working on a hotel website using the user-friendly WYSIWYG site builder, Wix (yes, I know, don't judge). Like all hotel websites, we need a form for customers to enter their details for reservations and other purposes. However, there&a ...