Home > other >  Ajax isn't fetching the text file
Ajax isn't fetching the text file

Time:02-01

<!DOCTYPE html>

<head>
    <title>
        Ajax Joke of the Dya application
    </title>
    <script>
        var Request = false;
        if (window.XMLHttpRequest) {
            Request = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            Request = new ActiveXObject("Microsoft.XMLHTTP");
        }

        function RetrieveJoke(url, elementID) {
            console.log("Ret")
            if (Request) {
                var RequestObj = document.getElementById(elementID);

                Request.open("GET", url);

                Request.onreadystatechange = function() {
                    if (Request.readystate == 4 && Request.status == 200) {
                        RequestObj.innerHTML = Request.responseText;
                    }
                }
            }
        }
    </script>
</head>

<body>
    <h1> Where do bees go when they get married?</h1>
    <button type="button" value="Fetch Answer" onsubmit="RetrieveJoke('honeymoon.txt','Target')"> ANSWERRR</button>
    <form>
        <input type="button" value="Fetch Answer" onsubmit="retrieveJoke('honeymoon.txt', 'Target')" />

    </form>

    <div id="Target"> </div>
</body>

</html>

so it's a simple joke of the day application to learn ajax wherein the the button is supposed to fetch the answer and we deplo ajax for the same

here is the ajax code that's supposed to fetched "Honeymoon!" that's written in honeymoon.txt file when we click on the answer and fetch answer button but it isn't??? Please help

CodePudding user response:

You could just use this function

async function fetchData(path) {
  const data = await fetch(path); // Fetching file content
  return await data.text(); // Converting it to text and return
}

Then call it like this

const data = fetchData("./myfile.txt"); // Pass your file path here
console.log(data); // This will return your file content

So final answer could be

const button = document.querySelector("button"); // Your button
const result = document.querySelector("#Target"); // Your result div

button.addEventListener("click", function() {
  const data = fetchData("./honeymoon.txt");
  result.textContent = data;
});

CodePudding user response:

what is the url? you need a server to serve the file, the file system won't do.

  • Related