Pop-up triggered by AJAX XMLHTTPRequest

Essentially, I am attempting to create a fade in/out popup located in the corner of my webpage. For example, when John Doe logs online, I want a notification to appear. This is achieved by using AJAX to check for new updates and displaying the popup if necessary.

The jQuery function to display the popup is:

function hidepop(){
  $("#popup").fadeOut("slow");
}

function showpop(){
  $("#popup").fadeIn("slow");
  setTimeout("hidepop()",4000);
}

The code responsible for updating and showing the popup is as follows:

function getHTTPObject(){
  if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
  else if (window.XMLHttpRequest) return new XMLHttpRequest();
  else {
    alert("Your browser does not support AJAX. Please download Google Chrome or Firefox.");
    return null;
  }
} 

function checkUpdates(old){
  httpObject = getHTTPObject();
  var randomnumber=Math.floor(Math.random()*10000);
  if (httpObject != null) {
    link = "updates.php?rnd="+randomnumber;
    httpObject.open("GET", link , true);
    httpObject.onreadystatechange = function() {
      if(httpObject.readyState == 4){
        var response = httpObject.responseText;
        var objDiv = document.getElementById("popup");
        objDiv.innerHTML = response;
        if(response == old){
          var time = setTimeout(function(){checkUpdates(response); response = null},5000);
        }else{
          var objDiv = document.getElementById("popup");
          objDiv.innerHTML = response;
          showpop();
          var time = setTimeout(function(){checkUpdates(response); response = null},5000);
        }
      }
    }
  }
}

To initialize this process, add the following line to the body tag:

onload="checkUpdates('');" 

When implemented, nothing appears to occur. Although, I have verified that the popup can be shown successfully by calling showpop(). It seems like there may be a simple mistake causing this issue. Any guidance or suggestions on identifying and resolving the problem would be greatly appreciated.

Thank you, Calum.

Answer №1

To start, I recommend utilizing jquery's 'get' method, especially since you are already using jquery in your code.

var old = '';
function checkUpdates() {
    var randomnumber = Math.floor(Math.random() * 10000);
    link = "updates.php?rnd=" + randomnumber;
    $.get(link, function(data) {
        /* This function is called when the resource is successfully retrieved */
        if (old != data) {
            $('#popup').html(data); // Set the new data in the popup element
            showpop();              // Show the popup
            old = data;             // Store the retrieved data
        }
        setTimeout(checkUpdates, 5000);
    });
}

Your showpop and hidepop functions need to be corrected.
I suggest reviewing document.ready(...).

You can enhance the functionality by using jquery's delay function to chain everything neatly:

function hidepop(){
    $("#popup").fadeOut("slow");
}

function showpop(){
    $("#popup").fadeIn("slow");
    setTimeout(function() {hidepop();}, 4000);
}

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

Javascript: Insert a class declaration post loading of the page

When working with native web components, it is necessary to be able to add class definitions after the page has loaded, especially when new types of components are dynamically added to the DOM. EDIT: Here's a brief explanation: In order to define we ...

The absence of button.onclick=func in the HTML code is notable

I am facing an issue where adding an onclick attribute to an input element via JavaScript does not display in the HTML, but the function gets executed. On the other hand, when I add the input element directly in the HTML code, the onclick attribute shows u ...

Make sure to validate onsubmit and submit the form using ajax - it's crucial

Seeking assistance for validating a form and sending it with AJAX. Validation without the use of ''onsubmit="return validateForm(this);"'' is not functioning properly. However, when the form is correct, it still sends the form (page r ...

Having trouble with this code// Does anyone know how to make the div slide in line with other divs when hovering over it?

After spending countless hours analyzing and trying various solutions, I have come to the realization that I need to seek help with my code. The task at hand is proving to be incredibly frustrating, and I have exhausted all other options before resorting t ...

Updating the variable in Angular 6 does not cause the view to refresh

I am facing an issue with my array variable that contains objects. Here is an example of how it looks: [{name: 'Name 1', price: '10$'}, {name: 'Name 2', price: '20$'}, ...] In my view, I have a list of products bei ...

Issue with calling jQuery method from the view in C# not executing the function as expected

I am trying to implement jQuery in a view, but I am facing an issue where the backend method is not being triggered as expected. I need some additional eyes to help me figure out why it's not working properly. <script src="../Scripts/jquery-1.7.1. ...

Is there a method to automatically execute an 'onchange' function whenever a value is updated due to an AJAX response?

Many drop down menus are present on my page; <... onchange="callthisfunction(...)"...> While a manual change easily triggers the function, using ajax to load saved data does not register the value as changed and the function is not triggered. Is th ...

obtain data from JSON using JavaScript

Greetings! I am dealing with a JSON output that looks like this: "{ \"max_output_watts\": 150, \"frame_length_inches\": \"62.20\", \"frame_width_inches\": \"31.81\" }" I am using it in a functi ...

Ways to prevent websites from switching to landscape mode

Is there a way to prevent landscape mode on my website and restrict users to portrait mode, especially for devices with screen widths below 777px? I have custom headers that take up fixed position space of around 100px on the screen. If it is possible to ...

Create a dynamic div element using Jquery that is generated based on text input

I am attempting to dynamically insert a div based on the text within the parent container. My HTML structure is as follows: <div class="listing_detail col-md-4"><strong>Living Room:</strong> Yes</div> <div class="listing_detail ...

Easy peasy add-to-cart functionality using AJAX

Hey everyone, I'm trying to figure out how to add items to a cart and display them on the page without having to reload the entire page. It's been challenging for me, so I decided to start with a simple example to understand the logic better. In ...

Three.js: Objects in the distance appear more subtle

Currently, I am developing a three.js scenario that showcases textured point sprites. These sprites obtain their textures from a single uniform, which is a 2D canvas containing the alphabet: https://i.stack.imgur.com/Ceh9x.png In my scene, all the letter ...

Converting rotation into a directional vector

I have a Three.js object and I am able to read its rotation. However, I am looking for a way to extract a vec3 that indicates the direction in which the object is currently rotated. Can someone provide guidance on how to achieve this? ...

Transform the binary image data sent by the server into an <img> element without using base64 encoding

It's been a challenge trying to find a reliable method for adding custom request headers to img src, so I'm experimenting with manually downloading the image using ajax. Here is an example of the code I am working on: const load = async () => ...

Using Radio Buttons in a jqGrid Interface

Currently, I am attempting to integrate radio buttons within a jqGrid framework. I am aware that a custom formatter can be utilized for this purpose. Below is my code snippet, however, it fails to provide information on which radio button is selected or if ...

Dividing a JSON string and incorporating them into individual tds using AngularJS

Currently, I am working on extracting values from a JSON string by splitting it at the ":" and displaying the two values in separate td tags. function testCtrl($scope) { $scope.response = {"name":["The name field is required."],"param":["Hobby: Coding", " ...

Building an HTML table dynamically with JavaScript

Can anyone help me figure out why my JavaScript code isn't populating the HTML body table as expected? var shepard = { name: "Commander", victories: 3, ties: 1, defeats: 6, points: 0 }; var lara = { name: "RaiderOfTombs", victories: ...

How can I transform an array of text into dropdown options?

Currently, while utilizing Vue and vue-bootstrap, I am facing the task of populating a dropdown menu with an array of text items retrieved from my database. The <b-form-select> component in Bootstrap requires objects of the form {value: 'some va ...

The module "ng-particles" does not have a Container component available for export

I have integrated ng-particles into my Angular project by installing it with npm i ng-particles and adding app.ts import { Container, Main } from 'ng-particles'; export class AppComponent{ id = "tsparticles"; /* Using a remote ...

A role requiring coordinates x, y, and z with significant values

http://jsfiddle.net/eho5g2go/ var offset=10000000; ... camera.position.set(offset,offset,400); mesh.position.set(offset-300,offset,0); camera.lookAt(mesh.position); ... animate(); The "offset" variable is crucial for determining the camera and mesh p ...