What is preventing AJAX from displaying the updated JSON content?

I'm brand new to JavaScript and I'm trying to send an ajax request to retrieve the contents of a JSON file and display it in a div. Here's the code I currently have:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <title>Ajax 1 - Text File</title>
</head>
<body>
    <button id="button">Get Text File</button>   
    <br><br>
    <div id="text"></div>
    <script>
        document.getElementById("button").addEventListener('click', loadText);

        function loadText(){
			var xhr = new XMLHttpRequest();
			xhr.overrideMimeType('application/json');
			xhr.open('GET','users.json',true);
			xhr.onreadystatechange = function () {
			  if (xhr.readyState == 4 && xhr.status == '200') {
				result.innerHTML = '<pre><code>[
    {
        "id":1,
        "name":"Rick",
        "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="24564d474f644349454d480a474b49">[email protected]</a>"
    },
    {
        "id":2,
        "name":"Negan",
        "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="46282321272806212b272f2a6825292b">[email protected]</a>"
    }

]

The code works properly but I'm facing an issue where even after manually updating the users.json file, the browser still displays the old version. What could be done to resolve this problem?

Answer №1

There is a possibility that the browser may be returning a cached response.

To ensure updated content, you can try adding a 'timestamp' parameter to each new request made to the server.

document.getElementById("button").addEventListener('click', loadText);

function loadText() {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', 'users.json?ts=' + Date.now(), true);

  xhr.onload = function() {
    if (this.status == 200) {

      document.getElementById('text').innerHTML = this.responseText;
    } else if (this.status == 404) {
      document.getElementById('text').innerHTML = 'not found';
    }
  }
  xhr.send();
}
<button id="button">Get Text File</button>
<br><br>
<div id="text"></div>

If jQuery is included on your webpage, it is recommended to use the jQuery version of ajax. To prevent caching results, set cache to false.

$.ajax({
    url: 'myurl',
    type: 'GET',
    dataType: 'json',
    data: jsonDataObject,
    cache: false, // Appends _={timestamp} to the request query string
    success: function(data) {
        // data is a json object.
    }
});

Answer №2

Consider enabling the disable cache option in the network panel of your developer tools.

This issue could be related to the caching mechanism of your web server.

Answer №3

Make sure to include the header

content_type="application/json"

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

Understanding the lockfile: deciphering the significance of each line in the yarn.lock file

I'm curious about the meaning of each line in this file. I encountered issues with packages due to dependencies in my project. After upgrading nuxt from version 1x to 2x, all tests started failing. After spending hours searching online, I discovered ...

AngularJS - Choose and establish initial values for Editing or Creating New Items

My first project involving AngularJS has left me a bit stuck when it comes to using the select list. I need to either set the default value to the first option for a new entry, or if it's an edit, select the appropriate value. In my form, there are t ...

What is the process for implementing JavaScript in Django?

I'm a newcomer to this and although I've tried searching on Google, I haven't found a solution. I'm facing an issue where I can include JavaScript within the HTML file, but it doesn't work when I try to separate it into its own fil ...

The script fails to start using npm start, however, it runs smoothly when using node server.js

For a while now, I've been facing an issue that I just can't seem to resolve. When I navigate to my project's src folder and execute `node server.js`, everything functions as expected. I can access the application at http://localhost:3000/cl ...

Clones are made sortable instead of arranging them in a specific order

I have a list that can be sorted with some customizations. However, I am facing an issue where the items in the list get duplicated every time I try to sort them. When I pull one item to sort it, another copy gets added automatically. I am struggling to u ...

Using AJAX to retrieve Laravel Route results in incorrect URL leading to 404 Error (Not Found)

I am experiencing an issue with my route setup in web.php. Here is the route definition: Route::delete('/contributions/contribution/destroy', 'ContributionController@destroy'); In my blade file, I have a button that triggers a sweetal ...

Learn the process of sending code to a database using AJAX

I am facing a challenge in saving HTML and Javascript codes to a Database using Ajax. I am unsure about the optimal way to do this. Writing all the codes as Strings for the variable seems cumbersome. Do you have any suggestions to simplify this process? & ...

The hyperlink to a different webpage does not trigger any JavaScript functionalities or render any CSS styles

I am facing an issue with linking HTML pages that run Javascript and JQuery Mobile from another HTML page. My link setup is as follows: <a href="hours.html">Hours</a> The linking page and the linked pages are in the same directory. However, ...

Javascript Callback function not working as expected

I'm attempting to include an anonymous callback function in my code. I know it might seem a bit messy. By typing into the intro section, it triggers the animation using the .typed method with specific parameters. What I'm struggling to do is imp ...

The meteorite experienced a crash as startup.js attempted to connect with Mongo

Setting up a Mongo database for a meteor project has been tricky for me. I've created a startup.js file to load the necessary files, but as soon as I start meteor, it crashes. Can anyone lend a hand, please? Here is a snippet from the HTML file: < ...

Begin the process of setting up PDF.js on the website

I've been attempting to incorporate PDF.js into my website, but I'm struggling to do it correctly. When I try to display the PDF file on the screen, I encounter this issue: https://i.sstatic.net/aixrP.png Although I can't see the PDF file ...

When the oncuechange event is triggered, it initiates a smooth fade-in/fade-out animation within the HTML P tag

Just starting out with web development and learning JavaScript. Trying to create a webpage that displays lyrics synced with an audio file inside a p tag. The subtitles are sourced from a vet file extension and I am using the "cuechange" event in JavaScript ...

Sending data from PHP to JavaScript using JSON encoding through POST requests

I am dealing with a multi-dimensional array that needs to be passed to a PHP script using JavaScript to parse JSON data and display it on Google Maps. I am experimenting with using forms to achieve this: <?php $jsontest = array( 0 => array( ...

How can data be efficiently transferred to d3 within the Node.js/Express framework to facilitate the rendering of graphical information?

Currently, I am using a jade file to pass data from JS files into it. Then, the jade file requires a JS file to handle the D3 code. I feel like this may not be the most appropriate way to handle this situation. I am hesitant to directly pull data from Mon ...

An error popped up while using the fetch API due to an unexpected end of input

fetch('http://www.freegamesforyourwebsite.com/feeds/games/?tag=platform&limit=100&format=json', { method:'GET', mode:'no-cors', dataType: 'json', headers: { 'Accept': 'a ...

I am unable to get JQuery UI Dialog to open on my end

Coding in HTML: <button type="button" class="btn btn-success" style="margin-bottom:14px" id="btnAdd" onclick="modaladdedit('URLToMyController')"><i class="fa fa-plus"> Add New</i></button> HEAD Tag Setup: <link rel=" ...

Presentation - hyperlink only functioning for final slide

I have a question about Lean Slider, which you can check out at My goal is to link each slide to a different URL. However, I'm facing an issue where only the code in the last slide seems to be executed and applied to all other slides. For example, if ...

Remove the initial x characters from a numerical value and verify if it aligns with a specified regular

I need to remove the initial 6 characters (numbers) from a number and verify if it matches any number on a given list. For instance, if we have a number input like: 1234567891234567 The first 6 characters extracted would be: 123456 Then I want to confi ...

Tips for transferring data from Controller to View using IEnumerable Model in MVC

Currently, I have a view containing 1700 records that need to be paginated using ajax for lighter page loading. The paging functionality works smoothly, bringing in a new set of records based on the selected page. Issue: The problem arises when displaying ...

Is there a way to acquire and set up a JS-file (excluding NPM package) directly through an NPM URL?

Is it feasible to include the URL for the "checkout.js" JavaScript file in the package.json file, rather than directly adding it to the Index.html? Please note that this is a standalone JavaScript file and not an NPM package. The purpose behind this appr ...