4

I'm trying to do a basic AJAX tutorial to read data from a file, hello.txt, into my webpage. hello.txt and my current html webpage are in the same directory. Does anyone know what I'm doing wrong? Nothing happens when I load the page.

<!DOCTYPE html>
<head><title>Ajax Test</title>
<script type="text/javascript">
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", "hello.txt", true);
    xmlHttp.addEventListener("load", ajaxCallback, false);
    xmlHttp.send(null);
    function ajaxCallback(event){
        alert( "Your file contains the text: " + event.target.responseText );
    }

</script>
</head>
<body>
</body>
</html>
Spanner
  • 41
  • 1
  • 1
  • 4
  • Is your textfile located under `http://example.com/hello.txt` where the request comes from `http://example.com`? – Sumurai8 Nov 02 '13 at 22:02
  • I just saved it in the same folder as my html file. When I upload it to my server my html page is http://www.example.com/~user/test.html and my textfile is http://www.example.com/~user/hello.txt – Spanner Nov 02 '13 at 22:05
  • 2
    Your code works flawlessly on latest FF & Chrome. – nietonfir Nov 02 '13 at 23:05

5 Answers5

1

here is a function i always use for simple async get ajax:

1.use onload as it's shorter to write and as you don't need to add multiple eventhandlers.

2.don't do syncronous ajax.

js

function ajax(a,b,c){//url,function,just a placeholder
 c=new XMLHttpRequest;
 c.open('GET',a);
 c.onload=b;
 c.send()
}

function alertTxt(){
 alert(this.response)
}

window.onload=function(){
 ajax('hello.txt',alertTxt)
}

example

http://jsfiddle.net/9pCxp/

extra info

https://stackoverflow.com/a/18309057/2450730

full html

<html><head><script>
function ajax(a,b,c){//url,function,just a placeholder
 c=new XMLHttpRequest;
 c.open('GET',a);
 c.onload=b;
 c.send()
}

function alertTxt(){
 alert(this.response)
}

window.onload=function(){
 ajax('hello.txt',alertTxt)
}
</script></head><body></body></html>
Community
  • 1
  • 1
cocco
  • 16,442
  • 7
  • 62
  • 77
  • That didn't do anything either – Spanner Nov 02 '13 at 22:06
  • the browser your using? "hello.txt" is in the same folder as the html file? – cocco Nov 02 '13 at 22:09
  • Yes, the hello.txt file contains the string "test" and is in the same folder as the html file. – Spanner Nov 02 '13 at 22:13
  • what browser are you using? – cocco Nov 02 '13 at 22:13
  • I'm using Chrome. I tried it in Safari too and it didn't work – Spanner Nov 02 '13 at 22:14
  • I copied and pasted that whole thing into a blank html page in the same directory as my hello.txt file and nothing happened :( – Spanner Nov 02 '13 at 22:19
  • both scripts (Hasan Alaca & me) should work. 1.create a new text file.. 2.your executing the html file from a server(like apache) or just doubleclicking the html file? – cocco Nov 02 '13 at 22:27
  • I'm just double clicking the html file. I tried uploading the files to an EC2 instance on AWS but that doesn't do anything either. – Spanner Nov 02 '13 at 22:29
  • @cocco: Your script doesn't work for me either. I get an error in the js console: `XMLHttpRequest cannot load file:///C:/[...]/hello.txt. Cross origin requests are only supported for HTTP.` Maybe because it's chrome? It works OK in firefox. – Luis A. Florit Mar 22 '14 at 13:35
  • you can't get files from file:// protocol.. you need to be on a server with http:// – cocco Mar 24 '14 at 00:22
0

Here is your answer.

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
        var allText = this.responseText;
        alert(allText);
    }
};
xhttp.open("GET", "filename.txt", true);
xhttp.send();
MeirDayan
  • 620
  • 5
  • 20
0

The below code may be useful for someone...

 <!DOCTYPE html>
 <html>
 <body>

 <h1>Load Data from text file </h1>

 <button type="button" onclick="loadDoc()">Change Content</button>

 <script>
     function loadDoc() {
       var xhttp = new XMLHttpRequest();
       xhttp.open("GET", "info.txt", true);
       xhttp.send();
       document.getElementById("demo").innerHTML = xhttp.responseText;
     }
 </script>

 </body>
 </html>
Kowsalya R
  • 280
  • 6
  • 10
-1

Open an empty .PHP file or .ASPX file (or just any server-side language that can run javascript)

Paste this code between "head" tags.

<script>
    var xmlhttp;
    function loadXMLDoc(url, cfunc) {
        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = cfunc;
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
    }
    function myFunction() {
        loadXMLDoc("hello.xml", function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
            }
        });
    }
</script>

As you see, javascript is referring to "hello.xml" file to get information from.

Open an empty XML file inside the project folder you have created in. Name your XML file as "hello.xml"

Paste this code to your XML file.

<?xml version="1.0" encoding="utf-8"?>
<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

Run your php (or .aspx) file on localhost.

Click on button, your page must acquire the XML data into your website.

Hasan Alaca
  • 232
  • 2
  • 14
  • I have the text "test" in hello.txt. I've tried that example but my button doesn't do anything – Spanner Nov 02 '13 at 22:01
  • I copied and pasted that entire thing into a blank html page and the button still doesn't do anything. I'm certain there's a textfile named hello.txt in the same directory too. My hello.txt file is just a plain text file I created in komodo that contains the string "test" – Spanner Nov 02 '13 at 22:11
  • Ok, thanks. Unfortunately I'm not allowed to use jQuery for this assignment :/ – Spanner Nov 02 '13 at 22:36
  • I've uploaded the files to my EC2 instance which is running Apache and it still doesn't work :( – Spanner Nov 02 '13 at 22:40
  • IF you "still" can't do it, just install teamviewer, I will do it on your computer. – Hasan Alaca Nov 02 '13 at 22:59
  • "or just any server-side language that can run javascript" = none except JavaScript itself. PHP or ASP files don’t run JS. They merely write text that’s then interpreted as JS code and executed by the browser. – bfontaine Oct 17 '17 at 12:18
-1

    function Go() {

        this.method = "GET";
        this.url = "hello.txt";

        if (window.XMLHttpRequest && !(window.ActiveXObject)) {
            try {
                this.xmlhttp = new XMLHttpRequest();
            }
            catch (e) {
                this.xmlhttp = false;
            }
            // branch for IE/Windows ActiveX version
        }
        else if (window.ActiveXObject) {
            try {
                this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                try {
                    this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (e) {
                    this.xmlhttp = false;
                }
            }
        }

        if (this.xmlhttp) {

            var self = this;
            if (this.method == "POST") {
                this.xmlhttp.open("POST", this.url, true);
            }
            else {
                //remember - we have to do a GET here to retrive the txt file contents
                this.xmlhttp.open("GET", this.url, true);
            }


            this.xmlhttp.send(null);

            //wait for a response
            this.xmlhttp.onreadystatechange = function () {

                try {
                    if (self.xmlhttp.readyState == 4) {
                        if (self.xmlhttp.status == 200) {
                            if (self.xmlhttp.responseText != null) {
                                self.response = self.xmlhttp.responseText;

                                alert(self.xmlhttp.responseText);
                            }
                            else {
                                self.response = "";
                            }

                        }
                        else if (self.xmlhttp.status == 404) {
                            alert("Error occured. Status 404: Web resource not found.");
                        }
                        else if (self.xmlhttp.status == 500) {
                            self.showHtmlError("Internal server error occured", "Status: " + self.xmlhttp.responseText);
                        }
                        else {
                            alert("Unknown error occured. Status: " + self.xmlhttp.status);
                        }
                    }
                }
                catch (e) {
                    alert("Error occured. " + e.Description + ". Retry or Refresh the page");
                }
                finally {

                }
            };

        }
    }


    //Use the function in your HTML page like this:

    Go();

</script>
UberGeoff
  • 192
  • 6