Converting a Click Event to a Scheduled Event using JavaScript and AJAX

Currently delving into the world of AJAX & JavaScript, I have a question for the knowledgeable individuals out there.

I am curious to know how I can transform the code below from an OnClick event to a timed event.

For instance, I would like to refresh the content of the "showlist" DIV every 5 seconds...

I am aware that posting working code is not permitted here, but sharing my non-functional code would only add to the confusion.

I am gradually grasping the basics and any help or advice would be greatly appreciated.

<!DOCTYPE html>
<html>
<head>
<script>

function loadXMLDoc()
{

var xmlhttp;
if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
else
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
{

document.getElementById("showlist").innerHTML=xmlhttp.responseText;

}
}

xmlhttp.open("GET","playlist.php?t=" + Math.random(),true);
xmlhttp.send();

}
</script>
</head>

<body>

<h2>Ajax Testing...</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="showlist"></div>
</body>

</html>

Answer №1

To enhance the loadXMLDoc function, you can incorporate the use of setTimeout. Take a look at this sample:

function loadXMLDoc() {

    var xmlhttp,
        timer;

    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("showlist").innerHTML = xmlhttp.responseText;
        }
    };

    xmlhttp.onerror = function() {
        clearTimeout(timer);
    };

    xmlhttp.open("GET", "playlist.php?t=" + Math.random(), true);
    xmlhttp.send();


    timer = setTimeout(loadXMLDoc, 5000);
}

This function initiates an AJAX request and establishes a timeout of 5 seconds. Additionally, I included a basic onerror callback to reset the timer as needed.

Answer №2

Back in the day, I created a custom television that would change its 'screen' every 3 seconds automatically.

If you're interested, feel free to take a look at my code below:

// This is the div called myScreen
var myScreen = document.getElementById('myScreen');
// This is an array containing picture names
var myPics = ['img-screen1.png','img-screen2.png'];
// Checking the number of items in the array
var totalPics = myPics.length;
// The function that loops through and displays each picture one by one
var i = 0
function loop() {
    if(i > (totalPics - 1)){
        i = 0;
    }
    myScreen.innerHTML = '<img src="images/'+myPics[i]+'">';
    i++;
    loopTimer = setTimeout('loop()',3000);
}
loop();

Feel free to adapt this code for your own project. If you have any questions or need clarification, don't hesitate to reach out :).

Remember to update the array whenever you add new items to your showlist!

Answer №3

If you include this code snippet within the same script tag after your loadXMLDoc function, it will automatically execute and call your function every 5 seconds in a recursive manner. Using setTimeout ensures that the function is called repeatedly without missing any cycles, unlike setInterval which may skip a cycle if the JavaScript engine is overloaded:

(function doMeSelf(){
    setTimeout(function(){
        loadXMLDoc();
        doMeSelf();
    },5000);
})();

By encapsulating the function definition within parentheses followed by (), it creates an immediately invoked function expression.

To understand more about this concept, refer to the following question: What do parentheses surrounding an object/function/class declaration mean?

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 change the hover background of a select element in Chrome from its default setting to something else

Is there a way to remove the background color on hover and replace it with a different color? .drp-policydetails { border: 1px solid #dddddd; background-color: #ffffff; } <div className="form-group"> <select className="form-control drp-po ...

creating an interactive element that seamlessly integrates with a dynamic background image slideshow

Struggling to make this work correctly as a newbie in javascript. I need the background image to slide upon hover and stay active on its selected div when clicked. The html, css, and javascript I have currently work fine - when the user clicks on a div, a ...

Switching from constructors to Hooks in REACT

I am currently working on adding a modal example within a function in my project. I have a specific requirement to incorporate hooks instead of using the constructor in a class-based component. This is the code snippet with the class-based implementation: ...

A guide on using jQuery to iterate through 3 separate div elements

Seeking assistance with creating a dynamic loop for multiple divs (3 or more) using jQuery. The desired outcome is to have the main image div on the homepage rotate with other divs, changing both the background image and links within each div. I initially ...

The `forEach` method cannot be called on an undefined node.js

I have been developing a small study website but encountered an issue with the title. Despite extensive internet research, I have not been able to find a solution. The system I am using is Ubuntu with node.js, express, and mysql. app.js var fs = requir ...

What is the most effective way to manage ajax requests that are time-consuming to finish?

As I begin delving into developing processor-intensive web applications, I find myself facing the challenge of scaling up my current LAMP stack setup. My application, running on a web server with PHP code, needs to connect to a remote Windows machine using ...

How to show a placeholder in a select input using ReactJS

I'm currently trying to incorporate placeholder text into a select input field using ReactJS, but it doesn't seem to be working as intended. Here is the code snippet I am working with: <Input type="select" placeholder="placeholder"> ...

Resolve the Prototype_Pollution vulnerability detected by Checkmarx

When executing the code line window.location.search.substring(1) with the word 'substring(1)', an error related to Prototype_Pollution occurs. This error is caused by assigning external properties without proper validation, which can lead to obje ...

showing sections that collapse next to each other

I am currently designing a portfolio website using HTML, CSS, and vanilla JavaScript. I have implemented collapsing sections that expand when clicked on. However, the buttons for these sections are stacked vertically and I want to place them side by side. ...

How can you include a key event handler that specifically looks out for the Space key being pressed?

When a user presses the Enter key (and button is in focus), the button opens. However, I would like to also open the link button when the user presses the space bar. Buttons should be activated using the Space key, while links should be activated with the ...

Transform a list of file directories into a JSON format using ReactJS

I am developing a function that can convert a list of paths into an object structure as illustrated below; this script will generate the desired output. Expected Output data = [ { "type": "folder", "name": "dir1& ...

Extracting Parameters using JQuery's load Method

On a webpage, I am attempting to load a jsp page (another.jsp) within a div element while passing parameters. $("#div").load('another.jsp?a=1&b=2'); Despite trying various methods multiple times, I have not been able to get the desired outc ...

Customizing the background color of rows in Node.js XLSX using the npm package

I am currently working on a project that involves reading an Excel sheet and then coloring specific rows based on backend data. While I have successfully been able to read the sheet and create a new one with updated information, I am facing issues when try ...

Unexpected obstacles encountered when implementing the jqTouch JavaScript/AJAX combination on Android

In jqtouch, I'm using vanilla ajax calls to load multiple pages: <li class="arrow"><a href="folder/another/somepage.html" >BRAVIA HDTVs</a><small class="counter">2</small></li></li> I want to incorporate a v ...

React- hiding div with hover effect not functioning as expected

I'm having trouble using the :hover feature in CSS to control the display of one div when hovering over another, it's not functioning as expected. I've successfully implemented this on other elements, but can't seem to get it right in t ...

Adjusting the shadow on the inserted image

Currently, I am using fabric.js to manipulate images that are added to my canvas. The issue I am facing is with the shadow around the image not being even. The code I have tried so far is displayed below, but you can view what I am aiming for by clicking h ...

Mastering the art of seamless navigation within a single page through the magic of

I have two HTML pages: "Login.html" and "index.html". Instead of a normal href linking, I want the user to navigate to "index.html" when they click on the login button. Furthermore, I want the index page to be displayed within the codes of login.html, cre ...

Float and tap

Can someone assist me with my code? I have 4 identical divs like this one, and when I hover over a link, all the elements receive the same code. <div class="Person-team"> <div class="profile-pic-d"> <a cl ...

Using jQuery to create a Select All Checkbox that toggles a specific class

I have come across similar examples in the past, but I have been unable to make it work as intended. The examples I found only use standard checkboxes. I attempted to customize the checkbox using a sprite sheet by applying a class, but I am struggling to a ...

Undefined arguments are causing issues in the Local Directive Vuejs

I'm struggling to properly set up a directive in Vue.js by following an example I found online. <div id="hook-arguments-example" v-demo:foo.a.b="message"></div> Here's the directive within the main Vue App code: const app = new ...