Welcome folks today in this blog post we will be fetching
data of text file and display it in browser using ajax
xmlhttprequest object in javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an index.html
file and copy paste the following code
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>AJAX Fetch Text File</title> </head> <body> <div id="result">Hello World</div> <button onclick="fetchData()">Fetch Data</button> </body> </html> |
As you can see we have the div
with id result where we will loading the data of the text file. Now create the file.txt
file inside the root directory and write some text into it. Now we will be fetching the data of that file and display it inside the browser.
1 2 3 4 5 |
function fetchData(){ const xhttp = new XMLHttpRequest() xhttp.open('GET','file.txt',true) // asynchronously } |
As you can see we are first of all creating a new object of the XMLHttpRequest class and then we are opening a new method of Get to the path of the file.txt
and lastly we are providing the third argument to be true. Which means that the request is asynchornous. And now we need to define the onload
event when the request loads what should happen.
1 2 3 |
xhttp.onload = function(){ document.getElementById('result').innerHTML = this.responseText } |
As you can see we are attaching the onload
event where we are simply
attaching the dynamic data to the innerHTML
property of the div element. This is equal to the response
coming from the ajax request. It is stored inside the responseText
property.
Now for actually sending the ajax request we will be using the send()
method as shown below
1 |
xhttp.send() |