Dealing with the outcome of a synchronous AJAX request and displaying or concealing a div based on the result's value

I am attempting to run a JavaScript function that checks for internet connectivity status. If the user is connected to the internet, I do not want anything to happen on screen. However, if the connection is lost, I would like to display a div element.

The div will cover the entire screen, preventing the user from interacting with the page in the background until the connection is re-established. Once the connection is back up, the div should disappear automatically, allowing the user to interact with the buttons on the screen again.

To accomplish this, I have a JavaScript function that checks connectivity every second using an AJAX post to a PHP file. The PHP file echoes back "1" to the JavaScript, indicating an active connection. If no response is received, it signifies a broken connection and prompts the display of the div element called "openOfflineDIV."

Here is the snippet of my JavaScript code:


function checkConnection() {

    if($.ajax({
         url: 'php_scripts/checkconnection.php',
        type: "POST",
       async: false
       }).responseText == "1"){
           console.log("Connection active");       
         openOfflineDIV.style.visibility = 'hidden';
                               }
       else{
           console.log("Connection lost");
          openOfflineDIV.style.visibility = 'visible'; 
                                       }
       };

This setup seems to be causing a specific error related to synchronous XMLHttpRequest, even after modifying the code as suggested in various sources. I have also attempted different approaches to handle the situation without success.

If anyone could offer guidance or assistance in resolving this issue, I would greatly appreciate it. Thank you in advance!

Latest Update:

I made changes to my code based on a recommendation but encountered challenges getting the div to appear when the connection is lost. Although the console displays "disconnected" when appropriate, the div does not show up, leading me to seek further assistance in debugging the issue.

Answer №1

This is the basic framework for incorporating online and offline functionality into your project.

function checkConnection() {
    $.ajax({
        url: 'php_scripts/checkconnection.php',
        type: "POST",
        success: function() { $("#openOfflineDIV").hide(); },
        error: function() { $("#openOfflineDIV").show(); }
    }).complete(function () {    // this initiates the next connection check in 1 second
        setTimeout(checkConnection, 1000);
    });
});

$(document).ready(checkConnection);   // initiate the initial connection check on DOMReady

I have created a demo to showcase it.
Just disconnect your internet and observe how the status updates accordingly (you may also see a popup from jsfiddle for the same reason).

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

Dealing with numerous entries in an HTML form using PHP

Currently, I am learning the basics of HTML, PHP, and Javascript. I recently worked on creating a user profile form that includes fields like Full Name, Email Id, and Mobile number. I also want to incorporate a section for "Hobbies/Interests" where users ...

Incorporating external function from script into Vue component

Currently, I am attempting to retrieve an external JavaScript file that contains a useful helper function which I want to implement in my Vue component. My goal is to make use of resources like and https://www.npmjs.com/package/vue-plugin-load-script. Thi ...

Is it possible to generate an error if you attempt to retrieve a property that does not exist within a JavaScript object?

I am creating a new object with specific properties. I need to ensure that an error is triggered if the user attempts to retrieve a property that doesn't actually exist. Is there a way to achieve this in my code? ...

The functionality of CSS transform appears to be malfunctioning on Firefox browser

My website, located at , features a logo that is centered within a compressed header. I achieved the centering effect using the following CSS command: .html_header_top.html_logo_center .logo { transform: translate(-63%, -2%); } This setup works perfe ...

Combining a contact form with a Google Map div using the Bootstrap grid system

Hey there, I'm currently facing a challenge with grid placement as I try to position a Google map div next to my contact form. The struggle is real! <div class="container"> <div class="row"> <div ...

Passing a JSON object between pages in Next.js using props during programmatic navigation

In my Next.js project, I have two pages. On the first page, the user fills out a form to create a post. The information is stored in a large JSON object, which needs to be passed to the second page for the user to preview the post before finalizing it. Wi ...

Interaction between an Android app and a web page

Looking to develop a mobile app capable of sending messages and images to a webpage. Seeking guidance on how to bring this vision to life. Any assistance would be greatly appreciated in achieving this project. ...

Utilizing Subdirectories in a Command Manager

My goal is to organize my commands into sub folders, but for some reason my bot is not recognizing the commands inside those folders. Strangely, no error message is being displayed. const fs = require('node:fs'); const Discord = require('dis ...

Optimal method for parsing URLs using ES6

There have been many remarkable inquiries regarding this topic, such as: how to parse a url. However, as time has gone by, the answers I come across are outdated. I am looking for a more modern and flexible method to parse URLs, without relying on regular ...

Troubleshooting the issue of a callback function not properly updating state within the componentDidMount

I am currently utilizing Next.js and have the following functions implemented: componentDidMount = () => { //Retrieves cart from storage let self = this this.updateCart(Store.getCart(), self) ... } updateCart = (cart, self) => { ...

Increase a variable within a looping structure using jQuery

I am faced with a task that involves selecting two values from different dropdown lists, such as 1001 from the first dropdown and 1003 from the second. Upon clicking the 'add' button, I need to pass these selected values, along with the values in ...

Storing and Retrieving Multiple Data with localStorage

I need assistance with modifying my code. I have an input field labeled "mail" and I am trying to store email addresses and corresponding IDs in local storage. The email address should be taken from the "mail" input field while the ID should increment each ...

Retain the value of data.d even after executing the window.location command upon successful completion of the AJAX

I have been developing a small search box on website A that directs user input to website B for displaying the search results. I have set up a web method on website B to handle the parameters, and when calling this web method from site A, the query execute ...

Is it possible to include two functions within a single HTML script?

On my webpage, there are multiple tabs that display different sets of data. Below is the code for handling the functionality of these tabs: function openTab(event, tabName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassNa ...

Ensure child elements do not surpass parent size in HTML/CSS/Javascript without altering the children directly

I am intrigued by how iframes neatly encapsulate all site data within a frame and adjust it to fit the size. Is there any method to achieve this functionality in an HTML wrapper? Can the wrapper be configured so that regardless of the content, it is dis ...

Signing out in React js

Hey everyone! I'm facing an issue. I have to create a logout form on React js that redirects to loginindex.html from hello.ejs and clears some variables using server.js, but I'm not sure how to do it =( Can anyone offer some guidance? Thank you! ...

Retrieving data sent through an AJAX post request

My current project involves making a POST call from a basic HTML page to a Node.js and Express server that will then save the input values to a MongoDB collection. The issue I am facing is that when passing two POST parameters, namely 'name' and ...

The function is not being invoked, utilizing jQuery's .delegate method

Utilizing jquery delegate to call a function is effective. For example: $("body").delegate("div", "mouseover", function(){ alert("it works"); }); It also makes sense to reuse the same function in multiple places. Instead of duplicating the code, you can ...

What is the method for transferring the value of a jQuery variable to a PHP variable without using AJAX?

Here is my JavaScript code: $('#affiliates_name').change(function(){ var id = $('#affiliates_name').val(); }); Below is the corresponding HTML: <select id="affiliates_name" style="display: none;" name="affiliates_name"> < ...

Code snippet for a click event in JavaScript or jQuery

I initially wrote the code in JavaScript, but if someone has a better solution in jQuery, I'm open to it. Here's the scenario: I have multiple questions with corresponding answers. I want to be able to click on a question and have its answer dis ...