Table of Contents

    Fetching Data from Text Files Using AJAX and JavaScript

    Fetch data from text file - AJAX and Javascript

    HTML Code

    
    <!doctype html>
    <html lang="en">
    
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">  
        <title>Hello, world!</title>
    </head>
    
    <body>
        <h1>Hello, world!</h1>
        <div id="demo">
            This is demo Div
        </div>
        <button type="button" onclick="loadDoc()">Change Content</button> 
        <script src="script.js"> </script>
    </body>
    
    </html>
    

    JAVASCRIPT Code

    
    function loadDoc() {
        const xhttp = new XMLHttpRequest();
    
        xhttp.onload = function() {
          document.getElementById("demo").innerHTML = this.responseText;
        }
        
        xhttp.open("GET", "textfile.txt");
        xhttp.send();
      }
    

    All modern browsers support the XMLHttpRequest object.

    The XMLHttpRequest object can be used to exchange data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

    A callback function is a function passed as a parameter to another function. In this case, the callback function should contain the code to execute when the response is ready.

    
    xhttp.onload = function() {
      // What to do when the response is ready
    }