How to fetch information from a normal file with AJAX?

Asked 19-Aug-2021
Viewed 508 times

1 Answer


1

<!doctype html>

<html lang='en'>
<head>
    <!-- Required meta tags -->
    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <!-- Bootstrap CSS -->
    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css' rel='stylesheet' integrity='sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC' crossorigin='anonymous'>
    <title>Ajax Example</title>
</head>
<body>
    <div class='container mt-3'>
        <h1 class='text-center'>Ajax Example </h1>
        <button type='button' onclick='loadResponseText()' class='btn btn-primary my-3'>Click me for see the details of selected page</button>
        <h3 class='text-danger '>See details of of page</h3>
        <p class='text-primary'>Whole information of page <span id='details' class='text-muted'></span></p>
        <p id='loadAjaxInText' class='text-center'>call ajax without reload the page</p>
    </div>
    <script>
        function loadResponseText() {
            // creating instance of XMLHttpRequest()
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    // call responseXML
                    document.getElementById('details').innerHTML = this.getAllResponseHeaders();
                    document.getElementById('loadAjaxInText').innerHTML = this.responseText;
                }
            };
            xhttp.open('GET', 'ajademo.txt', true);
            xhttp.send();
        }
     </script>
    <script src='https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js' integrity='sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM' crossorigin='anonymous'></script>
</body>
</html>

ajademo.txt

<h1 class='alert alert-primary'>AJAX</h1>

<p class='text-danger'>AJAX is not a programming language.</p>
<p>AJAX is a technique for accessing web servers from a web page.</p>
<p class='bg-danger text-white'>AJAX stands for Asynchronous JavaScript And XML.</p>

Output

How to fetch information from a normal file with AJAX?