0

The logic:

my_function looks through file.txt, if it finds the word "Hello", returns true. If not, false.

The problem:

Uncaught type error: contents.includes is not a function

Limitations:

Can only use plain javascript

function my_function() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(contents) {
if (this.readyState == 4 && this.status == 200) {
//contents variable now contains the contents of the textfile as string

//check if text file contains the word Hello
var hasString = contents.includes("Hello");

//outputs true if contained, else false
console.log(hasString);

}
};
xhttp.open("GET",  "http://www.example.com/file.txt", true);
xhttp.send();
}
Malasorte
  • 1,153
  • 7
  • 21
  • 45
  • @Tushar If I use includes() with jquery GET function works. – Malasorte Oct 13 '16 at 03:15
  • Try `var hasString = contents.indexOf("Hello") > -1;` Also, check if `includes` is supported in your browser. – Tushar Oct 13 '16 at 03:16
  • You need to check if the "contents" is not empty/undefined add this: var hasString; if (contents !== undefined && contents !== "") { hasString = contents.includes("Hello"); } Make sure the result coming back is not empty. Checking the status is not enough in this context. – Ben Bozorg Oct 13 '16 at 03:19
  • @Malasorte Let me know if that works. Execute `'abc'.includes('a')` in browser and see if you're getting error or `true`. – Tushar Oct 13 '16 at 03:20
  • @Tushar I get true – Malasorte Oct 13 '16 at 03:26

1 Answers1

1

use this.responseText instead of that parameter contents
this.responseText is the response of your ajax

function my_function() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            //contents variable now contains the contents of the textfile as string

            //check if text file contains the word Hello
            var hasString = this.responseText.includes("Hello");

            //outputs true if contained, else false
            console.log(hasString);

        }
    };
    xhttp.open("GET",  "http://www.example.com/file.txt", true);
    xhttp.send();
}
Beginner
  • 4,118
  • 3
  • 17
  • 26