Update the display using a button without the need to refresh the entire webpage

I am currently working on a website project that requires randomized output. I have successfully implemented a solution using Javascript, but the output only changes when the page is reloaded. Is there a way to update the output without refreshing the entire page, possibly by clicking a button? Below is my existing code:

    <DOCTYPE html>
    <html>
        <head>
            <title>Strat Roulette - R6S Edition</title>
            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
            <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
            <link rel="stylesheet" href="strats.css">
            <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<script>
var request = new XMLHttpRequest();
request.onload = function() {
    // get the file contents
    var fileContent = this.responseText;
    // split into lines
    var fileContentLines = fileContent.split( '\n' );
    // get a random index (line number)
    var randomLineIndex = Math.floor( Math.random() * fileContentLines.length );
    // extract the value
    var randomLine = fileContentLines[ randomLineIndex ];

    // add the random line in a div
    document.getElementById( 'strats-output' ).innerHTML = randomLine;
};
request.open( 'GET', 'strats.txt', true );
request.send();
</script>
        </head>

        <body>
            <div id="content">
                <div class="textshadow">
                    <h1>Strat Roulette</h1>
                    <h2>Rainbow 6 Siege Edition</h2>
                </div>
                <div id="strat">
                        <code><div id="strats-output"></div></code>
                </div>
                <button type="button" class="btn btn-primary" onClick="window.location.reload()">Get New Strat</button>
                </div>
            </body>

            <footer style="clear: both;">
            <p class="alignleft">&#169; Skiletro <?php echo date("Y"); ?></p> <p class="alignright"><a href="./strats.txt">strats.txt</a></p>
            </footer>
</html>

Answer №1

function fetchRandomStrat(){
  var request = new XMLHttpRequest();
request.onload = function() {
    // grab the file content
    var fileContent = this.responseText;
    // split into lines
    var fileContentLines = fileContent.split( '\n' );
    // get a random index (line number)
    var randomLineIndex = Math.floor( Math.random() * fileContentLines.length );
    // extract the value
    var randomLine = fileContentLines[ randomLineIndex ];

    // display the random line in a div
    document.getElementById( 'strats-output' ).innerHTML = randomLine;
};
request.open( 'GET', 'strats.txt', true );
request.send();
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
            <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
            <link rel="stylesheet" href="strats.css">
            <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<script>
</script>
            <div id="content">
                <div class="textshadow">
                  
     <button onclick="fetchRandomStrat()">REFRESH CONTENT</button>
                    <h1>Strat Roulette</h1>
                    <h2>Rainbow 6 Siege Edition</h2>
                </div>
                <div id="strat">
                        <code><div id="strats-output"></div></code>
                </div>
                <button type="button" class="btn btn-primary" onClick="window.location.reload()">Gimme New Strat</button>
                </div>
            </body>

            <footer style="clear: both;">
            <p class="alignleft">&#169; Skiletro <?php echo date("Y"); ?></p> <p class="alignright"><a href="./strats.txt">strats.txt</a></p>
            </footer>

Furthermore, you might want to trigger it on page load as well.

You can simply encapsulate the request logic in a function and call it when the button is clicked.

Answer №2

To execute your AJAX code, create a function and call it when the button is clicked:

function fetchNewData(){
    var request = new XMLHttpRequest();
    request.onload = function() {
      // Retrieve file contents
      var fileContent = this.responseText;
      // Split into lines
      var fileContentLines = fileContent.split( '\n' );
      // Get a random index (line number)
      var randomLineIndex = Math.floor( Math.random() * fileContentLines.length );
      // Extract the value
      var randomLine = fileContentLines[ randomLineIndex ];

      // Display the random line in a div
      document.getElementById( 'strats-output' ).innerHTML = randomLine;
  };
  request.open( 'GET', 'strats.txt', true );
  request.send();
  }

Next,

<button type="button" class="btn btn-primary" onClick="fetchNewData()">Get New Strategy</button>

Check out this codepen link:

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

Converting keyValue format into an Array in Angular using Typescript

Is there a way to change the key-value pair format into an array? I have received data in the following format and need to convert it into an array within a .TS file. countryNew: { IN: 159201 BD: 82500 PK: 14237 UA: 486 RU: 9825 } This needs to be transf ...

Prioritize returning AJAX data over iterating through the parent loop

Hey everyone, I'm having trouble wrapping my head around this issue even after researching various scenarios online. Here's what's going on: I have an array of strings named recipientsList. What I want to do is make an AJAX call for each s ...

When the webpage is refreshed, a PHP code embedded within JavaScript is executed instead of waiting for a

This particular code is designed to toggle the chat feature on and off. The issue I am encountering is that it automatically toggles the chat on or off each time the page is refreshed. Ideally, it should only trigger when a user clicks on a specific link ...

Having trouble navigating through multiple layers of nested array data in react js

I need help understanding how to efficiently map multiple nested arrays of data in a React component and then display them in a table. The table should present the following details from each collection: title, location, description, and keywords. Below ...

Navigating through parent folder HTML files from child folder HTML files

Seeking guidance as I embark on a new project! Check out this link to see my skills in action: collegewebsite.zip Now for the query at hand. I am working on a project named Coffee Cafe for my tuition assignment. It involves utilizing CSS and HTML with J ...

Struggling to establish a functioning proxy in my React and Node application

In the process of developing a react client app with a node.js express backend, I have encountered an issue related to project structure. The client app includes a proxy configuration in its package.json file: "proxy": "https://localhost:5000" However, ...

Adjust the browser zoom level to default when navigating to a new page

My mobile site uses ajax to load pages, and I'm looking to implement a feature that resets the zoom level when a page changes. Is there an effective way to detect if a user has zoomed the view while browsing a page? Currently, I have been able to ch ...

What is the process for removing a specific row from a datatable?

I have implemented a data-table using Vue and Vuetify. When I click on the delete icon in a specific row, a snackbar pops up with two buttons - yes and no. If I click on the yes button, I want to delete that specific row. How can I achieve this functionali ...

TimeStamp Recorder - Typescript

I'm trying to create a timer that counts the time when a button is pressed. Currently, I have managed to display the minutes and seconds on the screen as soon as the button is clicked. For example: 21(min):02(sec) What I am struggling with is updati ...

Implementing raw static HTML files in webpack: a step-by-step guide

Recently, I created a basic template called test.html <div>raw text with content</div> All I'm trying to achieve is to import the raw file without any alterations For example: require('./test.html'); // This should return "&l ...

"Quotes are essential in Javastript syntax for specifying string values

I need to implement a JavaScript syntax to generate unique URLs for each image. The Robohash website provides random robot images based on different URL endings. I tried the code below, but it seems like ${props.id} is being interpreted as part of the UR ...

Continuous loop of images displayed in a slideshow (HTML/JavaScript)

Greetings everyone, I am currently working on creating an endless loop slideshow of images for my website. Despite researching several resources, I am still struggling to get the code right. The issue I am facing is that only the image set in the HTML code ...

Discover how to display the loading time and memory usage of a web page on the footer using the jQuery and AngularJS library

Does anyone know how to display the loading time and memory usage of a web page in the footer using jQuery and AngularJS libraries? I've managed to show the loading time with this jQuery code: <script type="text/javascript"> before = (new Date( ...

The tooltip for the Google+ button stopped working

After setting up my Portfolio, I added a Google+ button. However, the page lacks styling and there seems to be an issue with the tooltip causing delays. Can anyone help me identify where the problem lies? ...

Can a CSS hover effect transition modify the color scheme?

I have multiple buttons on a single page, and I want the hover effect to be applied to all of them with just one code using jQuery. Please review my code below. $(document).ready(function(){ $('.button').hover(function(){ var bc=$(this ...

Tips for incorporating personalized form and input directives in AngularJS while addressing issues with transcluded scope

Over the last few days, I attempted to implement something along these lines: %myform(name='somename' ng-controller='whatever') %myinput(ng-model='user.firstName' ... The controller has a user structure with firstName, l ...

An expected expression was encountered near the if condition

I am encountering an expression expected error in Visual Studio near if(isNullOr ........ if (value) { if (isNullOrUndefined(x.value) && isNullOrUndefined(x.value2)) { x.minMark + '-' + a + '*' + x.b + ' ' + ...

Updating the color of text when clicking on a link using javascript

I am facing an issue where I cannot seem to change the text color using JavaScript. The functionality to show and hide div tags is working perfectly, but changing the color seems to be a challenge. It's worth noting that there are no styles defined fo ...

Efficiently centering content in a grid layout using automatic fit repetition for optimized responsiveness

I've implemented a responsive grid where each item has its own hidden details section that is revealed upon clicking the item. The structure of the HTML/CSS setup is as follows: <div class="grid"> <div class="item"> ...

The Navbar's Toggle Icon Causes Automatic Window Resize

I implemented a mobile navigation bar using React and JS that slides in from the left when clicked. However, I encountered two issues: whenever I click on a menu button in the navbar or when my ad carousel moves, the window resizes for some reason. Additio ...