JavaScript and PHP utilize Ajax to keep track of previously loaded content

I'm encountering a strange issue that I've been trying to troubleshoot for some time now with no luck. I'm currently developing a website and have decided to load each subpage (content) dynamically using AJAX, including .js and .css files for each subpage. However, whenever I make changes to scripts or CSS files in one of the subpages and refresh the page, the changes don't seem to take effect. It's almost as if AJAX is somehow remembering the previous version. Oddly enough, when I leave it alone for a while and come back later, the changes miraculously appear. Any thoughts on what might be causing this? I want to ensure that there's no cache or memory retention interfering with my development process. I should note that I'm not using jQuery; instead, I'm relying on pure JavaScript and my own custom function for AJAX connection. Could there be something missing from my function? Here it is:

function sendQuery( data )
{
    var http = new XMLHttpRequest();
    var url = data["url"];
    var params = "";
    var query = data["params"];
    for(var key in query)
    params+=key+"="+query[key]+"&";
    params=params.substring(0,params.length-1);
    http.open("POST", url, true);
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http.setRequestHeader("Content-length", params.length);
    http.setRequestHeader("Connection", "close");
    http.send(params);
    http.onreadystatechange = function()
    {
        if(http.readyState == 4 && http.status == 200)
        {
            data["result"](http.responseText);
        }
    }
}

Answer №1

It seems like there may be a caching issue at play here. One solution could be to add the current time or a random string as a separate parameter to the request in order to ensure a higher level of uniqueness and prevent the response from being cached by the browser.

For example, you could use something like '?nocache='+new Date().getTime()

In addition, consider preventing the server side response from caching the content returned by setting headers like:

response.setHeader( "Pragma", "no-cache" );
response.setHeader( "Cache-Control", "no-cache" );
response.setDateHeader( "Expires", 0 );

Answer №2

It appears to be closely linked to your caching policy.

If you are hosting a site with apache,

Take a look at the .htaccess file in your root directory, where you may find something similar to this:

# Set up 2 Hour caching on commonly updated files
<FilesMatch "\.(xml|txt|html|js|css)$">
ExpiresDefault A7200
Header append Cache-Control "proxy-revalidate"
</FilesMatch>

The configuration above sets the expiration time to 7200 seconds = 2 hours.

To disable caching during development:

# Force no caching for dynamic files
<FilesMatch "\.(xml|txt|html|js|css)$">
ExpiresActive Off
Header set Cache-Control "private, no-cache, no-store, proxy-revalidate, no-transform"
Header set Pragma "no-cache"
</FilesMatch>

Then it should function correctly.

Another option is to modify this line:

var url = data["url"];

To:

var url = data["url"]+"&ts="+(new Date().valueOf());

To prevent caching. Note: this is just pseudo code. In case there isn't one already, "?" should be handled.

I hope this information proves helpful :)

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

The state in Reactjs is not displaying as expected

Check out my ReactJS todo app that I created. However, I am facing an issue with deleting todos. Currently, it always deletes the last todo item instead of the one I click on. For example, when trying to remove 'Buy socks', it actually deletes ...

What is the best way to reduce the size of my JavaScript files within my framework?

I have developed a custom PHP framework from scratch. The framework includes views, controllers, and models. Within the views, there are variables that can be set accordingly. $js = array('custom/testimonial.js','jquery.js'); Within ...

Having trouble with my JavaScript code in Visual Studio because of a bundler issue. It's throwing an Uncaught ReferenceError for trying to access a variable before initialization

My AJAX request looks like this: $.ajax({ method: 'GET', url: '/api/some-data', headers: { 'Content-Type': 'application/json' }, success: function(data) { if (data != null) { var userDat ...

What could be causing the unexpected "undefined" result when trying to retrieve values from my array

Let me give you a brief overview. I am currently working on a Calendar app using React, react-calendar, and date-fns. My current challenge involves extracting values from an array of objects within a forEach loop. Here is the array in question: datesToAd ...

How can I find the week of the month using Moment.js? (similar to Google Calendar)

Currently leveraging the fantastic features of Moment.js, I am facing a dilemma. How can I determine which week of the month a particular date falls into? The documentation for Moment js only seems to provide information on "week of year." For instance, if ...

When transmitting data through ajax, escape characters are seamlessly included

I am looking to pass the SQL condition statement using the id of the link element, which represents the category of the product. This information will be processed by a PHP file and then loaded back into the div with the class load_area. To achieve this, I ...

Tips for updating information within a vue-component

I am working on a Vue component where I retrieve data from localStorage. Here is how I handle it: if (localStorage.getItem("user") !== null) { const obj_user = localStorage.getItem('user'); var user = JSON.parse(obj_user); } else { ...

Dynamic font sizing in CSS allows text on a webpage to

I am working on creating a dynamic screen using AngularJS. Within this screen, there are objects with a specific size: .item { margin: auto; margin-bottom: 10px; width: 11vw; height: 11vw; text-overflow: ellipsis; overflow: hidden; } These i ...

Angular Translate - Utilizing translate-values attribute for translation

Having trouble using angular translate with dynamic translation values that need to be translated first. If you want a better explanation of the issue, check out this plunker: PLUNKER <p translate="PARAGRAPH" translate-values="{username: ('us ...

Ensuring proper execution of the next callback function in an Express get request

I am currently running an express server on nodejs with a specific file structure that I need to convert into a list of links. Included below are my recursive functions for dealing with the file structure. Here are the file structure functions: function ...

When utilizing the AjaxExtension command, there seemed to be a discrepancy with the type RouteValueDictionary, as it is supposedly defined in system.web but could not be located

An issue with ASP.NET MVC and C# has led to an error in the title Here is the specific error that occurred I am attempting to implement Ajax, but unfortunately it is not functioning as expected; Visual Studio is unable to recognize the Ajax syntax ...

What is the best way to automatically show the last two digits of a phone number in a second text field?

Is there a way to automatically display the last 2 digits of a phone number input into the first text field onto the second text field using AJAX, JavaScript, or jQuery? I am looking for a script for my website similar to what was shown in this video. I ...

In search of a React.js/Redux OpenID library or example, particularly focused on Steam OpenID integration

Currently, I am developing a Node/Express REST + React/Redux application that requires Steam OpenID for authentication. Despite searching extensively for tutorials, libraries, or example code related to Steam OpenID (or any other OpenID), I have come up em ...

JavaScript Subscribe / Unsubscribe Button

I am trying to create a simple JavaScript program that allows users to like and dislike content. However, I am new to JavaScript and finding it a bit challenging. Basically, when the user clicks on the Follow button, the "countF" variable should increase ...

Issue with Vue: After removing an item from a v-for list, there is a remnant

Can you help me solve this issue with my Vue component setup? I have a list of components, each consisting of a preview canvas, a name, and a delete button. These components are stored in Vuex. For example, the list could look like this: | [W] Item 1 ...

Error: Attempting to access a property called 'name' on an undefined variable leads to a TypeError

I am a beginner with MongodB and nodejs. I have successfully implemented the GET method, which returns an empty array. However, when I tried to use POST in Postman for "categories," I encountered this error message: ExpressJS categories route app.js Err ...

The HTML video controls in Safari take precedence over the window.name attribute

When using Safari 8.0.5, the controls attribute for the video element will change the value of window.name to "webkitendfullscreen". This is significant because I rely on using window.name to store client-side data in Safari's private mode, where loca ...

Having trouble invoking an established route within a different route in an Express JS project

While working with an Express JS application connected to a mySQL database, I encountered an issue when trying to fetch data from a pre-defined route/query: // customers.model.js CUSTOMERS.getAll = (result) => { let query = "SELECT * FROM custo ...

The locomotive scroll elements mysteriously vanish as you scroll, leaving the footer abruptly cut off

After successfully implementing locomotive scroll on my website, I encountered some issues when uploading it to a live server. Elements started bumping into each other causing flickering and disappearing, with the footer being cut off as well. It appears t ...

Merging two sections of code? Transforming user inputted YouTube URL into an embedded URL and subsequently swapping out the iframe source with the modified URL

I am looking for a way to allow users to paste their YouTube URL into an input field, click submit, and have the video load above the input field. However, regular YouTube URLs do not work in iframes, so they must be converted using regex. I came across t ...