AJAX failing to retrieve data on a bluehost server

I have a dilemma with two basic web pages.

test.php:

<div id="demo"></div>


<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML =  this.responseText;
    }
  };
  xhttp.open("GET", "sse.php", true);
  xhttp.send();
}

var myVar = setInterval("loadDoc()", 2000);
</script>

sse.php

<?php
echo time();
?>

The issue is that it runs perfectly on my personal computer. Every two seconds, sse.php is fetched and the content in the demo-div updates accordingly.

However, when I try to run the same script on my Bluehost website, it only fetches once (after two seconds) and then stops working.

An interesting observation is that when I manually refresh the sse.php page in another tab, the content in the demo div changes! I've tried troubleshooting the problem but I'm running out of ideas.

Any suggestions or insights are greatly appreciated!

Thank you.

Answer №1

Upon conducting further investigation, I discovered that adding the following lines at the beginning of my sse.php file and then refreshing the page resolved the issue at hand. Much appreciated.

<?php
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

echo time();
?>

Answer №2

I encountered a similar issue which I detailed here:

AJAX function request causing interruption when called again - without using jQuery

Feel free to grab the code snippet I provided and test it out.

UPDATE:

An example call would be:

ajaxFetchData('http://someurl.com', 'targetElementId');

Also, here are the accompanying functions:

function ajaxFetchData(endpoint, elemId)
{
var req;
if (window.XMLHttpRequest) 
{ 
    req = new XMLHttpRequest();
} 
else if (window.ActiveXObject) 
{ 
    try 
    {
        req = new ActiveXObject('Msxml2.XMLHTTP');
    } 
    catch (e) 
    {
    try {
        req = new ActiveXObject('Microsoft.XMLHTTP');
    } 
    catch (e) {}
    }
}

if (!document.getElementById(elemId))
{
    return false;
}
var element = document.getElementById(elemId); /* <= update: added var */
showAjaxLoader(element);

/* EVENT HANDLERS COULD BE OMITTED IF NOT NEEDED */
req.addEventListener("progress", function(event){handleAjaxResponse(event, element)}, false);
req.addEventListener("load", function(event){handleAjaxResponse(event, element)}, false);
req.addEventListener("error", function(event){handleAjaxResponse(event, element)}, false);
req.addEventListener("abort", function(event){handleAjaxResponse(event, element)}, false);

req.onreadystatechange = function() 
{
    if(req.readyState === 4) 
    { 
        if(req.status === 200) 
        { 
            element.innerHTML  = req.responseText;
        }
        else
        {
            element.innerHTML = '<div id="'+id+'">Error loading data.</div>';
        }
    }
};
/* in my scenario, asynchronous AJAX request is used (true) */
req.open('GET', endpoint, true);
req.send(null);
}
/* LOADING ANIMATION CAN BE DISPLAYED HERE */
function showAjaxLoader(elem)
{
idBase = elem.id.split("_");
id = idBase[0]+"_loading_ajax";
elem.innerHTML = '<div id="'+id+'">Loading</div>';
}

/* OMITTING EVENT HANDLER FUNCTIONS IF UNNECESSARY */
function handleAjaxResponse(e) 
{
// Responding to each event type
switch(e.type)
{
    case 'error':
    {
        idBase = elem.id.split("_");
        id = idBase[0]+"_error_ajax";
        elem.innerHTML = '<div id="'+id+'">Server not accessible. Error loading data.</div>';
    } break;
}
}

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

Picture in a clear background without any alteration

Is there a way to create a background-color with opacity inside an image without affecting the image itself? The issue lies in the fact that the transparent background-color makes everything underneath it, including text and the image, transparent. Below ...

Limiting the scope of the jQuery scrollToFixed functionality within various nested DIV elements

I have been grappling with this issue for the past two days without success. I am utilizing the ScrollToFixed plugin from https://github.com/bigspotteddog/ScrollToFixed and my goal is to restrict the fixed positioning within a parent DIV. Despite scouring ...

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 ...

What is the reason behind Bootstrap 5's decision to have the getOrCreateInstance() method automatically toggle the collapsible element upon creation?

Today was my first encounter with the Collapse feature in Bootstrap 5, and I have to admit, I am not a fan! Imagine a scenario where I have a collapsible element that is initially hidden, and a button to toggle its visibility, like so: <button class=&q ...

Vuex failing to return object

I'm a newcomer to Vuex and I am facing issues while using a variable as a parameter to fetch card information from state.cards. store.js: export default new Vuex.Store({ state: { cards: [] }, getters: { getCard(state) { ...

CodeIgniter's feature of a dynamically dependent dropdown list

I am facing an issue with implementing three Dynamic Dependent Dropdown Lists in Codeigniter:- The first dropdown represents company names Based on the company selected, I aim to display that particular company's managers in another dropdown The thir ...

Issue with Ajax functionality not functioning properly in Visual Studio for Windows (Blend)

I am encountering an issue with my ajax login script. When I attempt to call the login function, nothing seems to happen... function login() { var login = new XMLHttpRequest; var e = document.getElementById("email").value; ...

The Bootstrap modal is not properly clearing all attribute properties when it is hidden

Alrighty, so I've got this modal set up: <div id="modal-container" class="modal fade" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content center-block" style="displ ...

Exploring a property within a JavaScript object

Within my code, I am working with an array of objects called user. When I try to log the first object using console.log(user[0]);, I receive this output: Object {activityId: "2", id: "1", activityDt: "01/15/2016"} Afterwards, I attempt to store user[0] in ...

Dynamic Visualizations with D3.js: Live Charts for Real-Time

This is my first time using D3.js and I am attempting to create a basic sparkline graph. The graph should have time on the X-axis and numbers up to 1000 on the Y-axis. I have a web socket server that sends random numbers up to 1000 to clients. My goal is t ...

Data from Firebase persists even after removal

Currently utilizing firebase for my project, where each user object includes their list of favorites. The structure is illustrated below: https://i.sstatic.net/vm6w8.png In the favorites object shown, there was initially two records, but one was manually ...

Optimizing Your HTML/CSS/JavaScript Project: Key Strategies for Modular

When it comes to web frontend projects (html/css/javascript), they are often perceived as more complex to read and maintain compared to Java/C#/C/C++ projects. Is it possible to outline some optimal strategies for enhancing the readability, modularizatio ...

Ensuring uniform sizing of anchor text using jQuery

My goal is to creatively adjust the font size of anchor text within a paragraph, making it appear as though the text is moving towards and away from the viewer without affecting the surrounding paragraph text. Currently, I am encountering an issue where th ...

Dealing with router parameters of an indefinite number in Angular 5: A comprehensive guide

Is there a method to efficiently handle an unknown number of router parameters in a recursive manner? For instance: We are dealing with product categories that may have subcategories, which can have their own subcategories and so on. There are a few key ...

Translating Angular strings from identical origins

I am currently utilizing angular-translate within my project. Within my views, there are several strings that I would like to translate, such as <ul> <li ng-repeat ="title.value as title in vm.states"> </ul> The array vm.states contai ...

Displaying a dynamic menu using Angular's ngFor loop

I am attempting to create a menu with sub-menus. The desired structure for my menu is outlined below. However, the demo I'm testing is not producing the correct structure. Check out the demo here. "Sub Test": { // Main menu "Example1":"hai",//sub ...

Using jQuery's post method in your WordPress website

I'm facing an issue with the code in my JavaScript file, located within a JS folder in my WordPress theme: jQuery('#tarieven-submit').on('click', function(event) { event.preventDefault(); var dest = jQuery('#destinat ...

Tips on embedding d3 into an HTML document

I am new to D3 and I would like to incorporate a simple line chart right after the table in my index.html file. <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="sheet.css"> <script src="jquery-1.1 ...

Avoid using the `target` attribute for `onclick` in Material UI components with React

Here is my current situation: The material UI component does not target my attribute on click. I am using the following button: <FlatButton containerElement="button" className="selectedNumberOfPeopleButton" onClick={this.selectedNumberOfPeople ...

When implementing multiple AJAX onclick calls, only one item is able to respond

Here is a snippet of my HTML code: <div class='delete-item' name='filetest' ></div> <div class='delete-item' name='anothertest' ></div> <div class='delete-item' name='coolfi ...