Adapting website content in real-time based on the information stored in a MySQL

Looking to update my website dynamically based on a value from the MySQL database in real-time. I currently have some code that partially achieves this functionality, but it seems to fail after a few calls by randomly switching between two values.

I have three PHP pages - one retrieves data from the database (database.php) and two generate responses based on the data (response1.php and response2.php). I verified that these pages return the correct values. The issue likely lies within my main HTML page below. I'm uncertain if the approach I've taken is optimal or if there's a better solution.

<html>
<head>
    <script type="text/javascript">
        var databaseanswer, xmlhttp;

        function databasecheck() {
            xmlhttp = new XMLHttpRequest();
            xmlhttp.open("GET", "database.php", true);
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    databaseanswer = xmlhttp.responseText;
                    document.getElementById("database").innerHTML = xmlhttp.responseText;
                }
            };
            xmlhttp.send();
        }

        function response() {
            if (databaseanswer == "No Tag") {
                xmlhttp = new XMLHttpRequest();
                xmlhttp.open("GET", "response1.php", true);
                xmlhttp.onreadystatechange = function() {
                    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                        document.getElementById("response").innerHTML = xmlhttp.responseText;
                    }
                };
                xmlhttp.send();
            }
            else {
                xmlhttp = new XMLHttpRequest();
                xmlhttp.open("GET", "response2.php", true);
                xmlhttp.onreadystatechange = function() {
                    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                        document.getElementById("response").innerHTML = xmlhttp.responseText;
                    }
                };
                xmlhttp.send();
            }
        }

        setInterval(databasecheck, 1800);
        setInterval(response, 2000);

    </script>
</head>
<body>
    <p> This is just a test site </p>
    <p> Response from server: </p>
    <div id="response">
    </div>
    <p> Answer from database: </p>
    <div id="database">
    </div>
</body>
</html>

Here's an updated version of my code:

<html>
<head>
<script>

function database(){
  var xmlhttp = new XMLHttpRequest();

  xmlhttp.open("GET","responsedatabase.php",false);
  xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
      {
        document.getElementById("database").innerHTML=xmlhttp.responseText;
      }
      }
  xmlhttp.send();
}

setInterval(database,1000);

</script>
</head>
<body>
<p> Answer from database: </p><div id="database"></div>
</body>
</html>

Answer №1

The issue arises from the multiple asynchronous requests being sent without proper serialization. It's important to note that the response times of these requests are unpredictable and tend to increase over time between the response and databasecheck invocations. For instance, initially, there might be a 200 ms difference between the execution of response (at 2 seconds) and databasecheck (at 1.8 seconds). As time passes, this gap grows larger, leading to potential inconsistencies in results.

In addition, the order in which requests are completed is not guaranteed due to lack of control over response times. Even if calls to databasecheck and response functions are serialized, uncontrolled XHR calls can result in erratic outcomes. This could lead to receiving correct or incorrect results based on the completion order of different requests.

To address these issues, it's crucial to serialize calls to databasecheck and response functions, ensuring that the call to response occurs only after the request to database.php is complete. Alternatively, consider consolidating the results from database.php, response1.php, and response2.php on the server-side to reduce the number of requests and eliminate synchronization problems.

Upon Update

Recommendations for your updated code:

var requestInProgress = false;
function database() {
    if(requestInProgress) {
        return;
    }
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.open("GET", "responsedatabase.php", false);
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
            requestInProgress = false;
            if(xmlhttp.status == 200) {
                document.getElementById("database").innerHTML = xmlhttp.responseText;
            }
        }
    }
    requestInProgress = true; 
    xmlhttp.send();
}

You may also consider adjusting the interval duration in the setInterval function to minimize delays between subsequent requests.

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

Error encountered with the OpenAI Chat Completions API: "The request could not be completed, status code 404"

Currently, I am in the process of developing an application similar to ChatGPT using React and Axios for API requests to OpenAI's Chat Completions API. However, I have hit a roadblock as I keep encountering a 404 error when attempting to make a reques ...

Issue encountered when attempting to send quotation marks to the web service using AJAX

Using .ajax, I am sending data with the following attributes: data: '{ "UserInput" : "' + $('#txtInput').val() + '","Options" : { "Foo1":' + bar1 + ', "Foo2":' + Bar2 + ', "Flags":"' + flags + '", "Im ...

How can the datetime value of the Apex Charts datapoint be shown in the tooltip?

I'm struggling to find the proper location within the w.globals object to display the x-axis value, which is a datetime, in the tooltip of the datapoint. var chartOptions = { ... xaxis: { type: "datetime" }, tooltip: { x: { format: " ...

The issue of uploading files using Ajax in CodeIgniter and Jquery is causing problems

I am attempting to implement a file upload using Ajax in CodeIgniter, but it seems like my Jquery code is not properly retrieving the data from the form even though the file appears to be included in the POST message. Below is my controller: public funct ...

Challenges in Ensuring Proper Alignment of Connection Line Between Boxes on Left and Right Sides within a React Component

Currently, I am developing a React component that displays two sets of boxes on the left and right sides of the screen. Users can choose one box from each side and click a "Connect" button to draw a line between them. However, I am encountering an issue wh ...

What is the process for retrieving randomized data using mongoose?

I recently came across the mongoose-random package which allows for retrieving a JSON array of random records using mongoose. My goal is to retrieve three random records with a specific field. Despite reviewing the documentation, I have yet to find a work ...

The issue with Jquery .html() function causing spaces to disappear between words

When utilizing jQuery's .html() property to populate a select box, I encountered an issue where the spaces between words were being trimmed down to just one space. Despite including multiple spaces in the option, it would always resolve to a single sp ...

Asynchronous update of array elements - lack of firing watch events

I have recently developed a component that showcases previews of blog articles. This particular component includes pagination functionality, where selecting a new page triggers the refreshment of the article previews array. The list of articles is obtained ...

Tips for exchanging divs in a mobile view using CSS

Illustrated below are three separate images depicting the status of my divs in desktop view, mobile view, and what I am aiming for in mobile view. 1. Current Status of Divs in Desktop View: HTML <div id="wrapper"> <div id="left-nav">rece ...

The module 'angular' could not be located and is causing an error

Currently, I am in the process of transitioning from Angular 1 to Angular 2 following this guide: . However, when I try to run the application using npm start, it displays an error saying 'Cannot find module 'angular''. This is a snipp ...

Failure to trigger a follow-up function in webSQL transaction's success callback

Review the code below. I have called setQuestion() within the successCallBack of db.transaction but am encountering an error: Uncaught TypeError: this.setQuestions is not a function. Can you spot any issues in my code? game.module( "game.scenes.scene" ) ...

Tips for avoiding a form reload on onSubmit during unit testing with jasmine

I'm currently working on a unit test to ensure that a user can't submit a form until all fields have been filled out. The test itself is functioning correctly and passes, but the problem arises when the default behavior of form submission causes ...

Having issue with jQuery popup not functioning correctly on the right side with the contact form. Is there anyone who knows how

Looking for a side slide popup that only accepts paragraph content? Want to add a contact form to it? Check out this fiddle - link here For a working example, visit - $(function() { // Slide from right to left $('#test2').PopupLayer({ ...

Exploring the world of design with React JS and MUI's diverse styling options

Exploring the various styling options offered by MUI From useTheme, styled, makeStyles to other methods - what sets them apart and how do they differ in use cases? We're looking for a comprehensive breakdown of their unique features, practical appli ...

Having trouble implementing min and max date validation in Angular UI-Bootstrap datepicker with UI-Bootstrap version 1.3.3

My goal is to implement validation in my datepicker, preventing the user from selecting a date within 30 days before or after the current date. Here's the code snippet I'm currently using for the datepicker: <div class="form-group" ng-class=" ...

Tips on dividing an Axios request into multiple files in ReactJS?

I've been working on a project that involves making Axios calls in multiple files, and I'm looking to modularize it by passing the call as a prop to other files that require it. Below is the componentDidMount() method containing the call: comp ...

Can anyone share a straightforward yet practical demonstration of using jquery.JsPlumb?

In my quest for a reliable graph-visualization JavaScript library, I recently came across jsPlumb at http://jsplumb.org. The examples I've seen truly showcase its advanced capabilities and attractive design. However, despite the extensive documentatio ...

The REST request is preventing the JavaScript on the page from executing

Utilizing REST to POST data through Firefox's Poster tool and encountering a url: http://[ip]/page.jsp?paramater1=whatever&parameter2=whatever (Content Type: application/x-www-form-urlencoded) The page.jsp includes: <body onload="onload()"&g ...

I am trying to figure out the best way to position the navbar directly under the jumbotron in Bootstrap 4

Obtaining information is possible with Bootstrap 3, yet I am struggling to understand how to implement it with Bootstrap 4. ...

Combine the outcomes of various AJAX requests into one variable

Looking to make 2 recursive API calls to create a JQuery datatables page with data from the range of 2016-2021. The API responses are split based on year filters to bypass the 5000 item list limit set by Sharepoint Online. Struggling to combine all API re ...