AbdallahRizk
AbdallahRizk

Reputation: 849

txt file wont load by using vanilla javascript

I am trying to implement an ajax with simple txt file but the file won't load any suggestion

the html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="app.js"></script>

<title>Ajax 1 - Text File</title>
</head>
<body>
<button id="button" onclick="loadText()">Get Text File</button>

</body>
</html> 

and the javascript file:

//Create event Listener of the Get Text File 


function loadText(){
// Create XHR object
var xhr = new XMLHttpRequest();
// OPEN - type, url/fileName, async
//console.log(xhr);
xhr.open('GET', 'sample.txt', true);

xhr.onload = function(){

    //HTTP statuses
    //200: OK
    //403: Forbiden
    //404: Not Found

    if(this.status == 200){
        console.log(this.responseText);
    }
    //Send Request
    xhr.send();
}
}

and this is the sample.txt file

This massage form the text file just to ensure you have the ability to 
access the text file. so if you do good for you otherwise just keep 
trying

Note, I'm trying to achieve it using vanilla javascript without any frameworks or library

As an output I get nothing once I click the button and even in the network tab in the inspector the txt file never even load.

enter image description here

Note, I'm using live sever on vscode

Upvotes: 0

Views: 225

Answers (1)

Sreekanth MK
Sreekanth MK

Reputation: 233

xhr.send() should be outside xhr.onload()

xhr.onload() is the callback function to be executed when the request completes successfully.

refer the docs here https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestEventTarget/onload

and the javascript file:

//Create event Listener of the Get Text File 


function loadText(){
// Create XHR object
  var xhr = new XMLHttpRequest();
  // OPEN - type, url/fileName, async
  //console.log(xhr);
  xhr.open('GET', 'sample.txt', true);

  xhr.onload = function(){

      //HTTP statuses
      //200: OK
      //403: Forbiden
      //404: Not Found

      if(this.status == 200){
          console.log(this.responseText);
      }
      //Send Request
  }
  xhr.send();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="app.js"></script>

<title>Ajax 1 - Text File</title>
</head>
<body>
<button id="button" onclick="loadText()">Get Text File</button>

</body>
</html> 

Upvotes: 1

Related Questions