GET function console error - javascript

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();
}

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();
}

Related

How to subset specific object properly in JS

I'm currently doing some practice and i want to print the titles of each movie on this api:
https://jsonmock.hackerrank.com/api/movies?Year=1998
Basically, I want each title to be printed for the first page (or preferably a specific page).
This is the code I have:
<script>
function printTItles(year) {
var res;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
res = JSON.parse(this.responseText);
for(var i=0;i<res.per_page;i++){
document.getElementById("demo").innerHTML = res.data.i.Title;
}
};
}
xmlhttp.open("GET", "https://jsonmock.hackerrank.com/api/movies?Year=<year>", true);
xmlhttp.send();
}
</script>
I know the problem is in res.data.i.title but I'm not sure how to fix it.
You are trying to access the element at the index i in your loop, like you would access a property of an object. To get the element at position i in your res.data array, you need the square bracket access [ ]
Also, you are not replacing the year parameters in your request for the year parameters passed to your function. You might want to check that out.
Here I have use the year 2018 as an example.
function printTItles(year) {
var res;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
res = JSON.parse(this.responseText);
for(var i=0;i<res.per_page;i++){
document.getElementById("demo").innerHTML = res.data[i].Title;
}
};
}
xmlhttp.open("GET", "https://jsonmock.hackerrank.com/api/movies?Year=2018", true);
xmlhttp.send();
}
printTItles();
<div id="demo"></div>
You could add some more improvement. For example, at each iteration, you are replacing the content of your #demo element. This cause only the last title to be shown. You could, instead, append the data to the already existing html of the div. Or, like I did in this case, build your string before setting it as the new innerHTML value.
function printTItles(year) {
var res;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
res = JSON.parse(this.responseText);
var output = "";
for(var i=0;i<res.per_page;i++){
if(res.data[i]) {
output += res.data[i].Title + '<br />';
}
}
document.getElementById("demo").innerHTML = output;
};
}
xmlhttp.open("GET", "https://jsonmock.hackerrank.com/api/movies?Year=2018", true);
xmlhttp.send();
}
printTItles();
<div id="demo"></div>
I've also added a condition to check if there is an element at res.data[i].

I can't use a Object, which was previously loaded via AJAX Request, in a function call

I'm trying to write a chrome extension, that closes a tab when it's loaded and contains specific keywords, which I'm storing in banned.json. But following code gives me an error:
//background.js:
var obj;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(xhttp.readyState == 4 && xhttp.status == 200){
obj = JSON.parse(xhttp.response);
console.log(obj.banned);
}};
xhttp.open('GET', "banned.json", true);
xhttp.send();
chrome.webNavigation.onCompleted.addListener(closeTab, obj.banned); // error is here
function closeTab(e) {
if (!e.frameId) {
console.log("Hallo2");
chrome.tabs.remove(e.tabId);
}
}
It says that it cannot read property banned of undefined. How can that be? obj is defined in the first line and I can reference it in the if-block. Can anyone help me?
EDIT:
banned.json:
{
"banned": [
"https://www.google.de/",
"youtube.com"
]
}
You need put "chrome.webNavigation.onCompleted.addListener" sentence in "xhttp.onreadystatechange" function.
var obj;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(xhttp.readyState == 4 && xhttp.status == 200){
obj = JSON.parse(xhttp.response);
console.log(obj.banned);
chrome.webNavigation.onCompleted.addListener(closeTab, obj.banned);
}};
xhttp.open('GET', "banned.json", true);
xhttp.send();
function closeTab(e) {
if (!e.frameId) {
console.log("Hallo2");
chrome.tabs.remove(e.tabId);
}
}
EDIT
You can try changing banned.json as follows.
{
"banned":
"url" : [
{"hostContains":"https://www.google.de/"},
{"hostContains":"youtube.com"}
]
}
Solution:
change banned.json to:
[
"www.google.de",
"www.youtube.com/?gl=DE"
]
"chrome.webNavigation.onCompleted.addListener" sentence mustn't be in "xhttp.onreadystatechange" function else you're gonna get an error.

XMLHttpRequest Replace Element Won't Work With LocalStorage

I tried to implement cookie logging with localStorage into the javascript code for replacing a specific element. It uses the XMLHttprequest method and, I got no idea why it won't work with localStorage. Please enlighten me.
localStorage.setItem("replace1", this.JSON.parse(responseText));
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("replace1").innerHTML = localStorage.getItem("replace1");
}
};
xhttp.open("GET", "yoinkexecutor2.php", true);
xhttp.send();
}
You can only display data when the async operation (GET) request terminates.
Otherwise you'll get undefined since nothing exits in the localStorage under that key
Also, you can only store strings in local storage, meaning you need to parse that object string once you want to retrieve the data using getItem
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
localStorage.setItem("replace1", JSON.stringify(this.responseText))
document.getElementById("replace1").innerHTML = JSON.parse(localStorage.getItem("replace1"))
}
};
xhttp.open("GET", "yoinkexecutor2.php", true);
xhttp.send();
}

Can't get JSON file into variable

I am trying to parse the content of the JSON file into a variable called weatherArray. However, this variable is always an empty array.
let weatherArray = [];
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
weatherArray = JSON.parse(this.responseText);
}
};
xhttp.open("GET", "https://fcc-weather-api.glitch.me/api/current?lon=55&lat=12", true);
xhttp.send();
}
/* Expecting the value to be stored and be shown in console*/
console.log(weatherArray);
You're checking the results before they come back. You need to move the line:
console.log(weatherArray);
To inside the onreadystatechange function, which will check the results once they arrive. Also you need to call the loadDoc() function (you probably did that).
let weatherArray = [];
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
weatherArray = JSON.parse(this.responseText);
console.log(weatherArray);
}
};
xhttp.open("GET", "https://fcc-weather-api.glitch.me/api/current?lon=55&lat=12", true);
xhttp.send();
}
loadDoc();
EDIT If you like to process the results in another function instead of inside onreadystatechange, you can call that function from onreadystatechange. You can do that with your global weatherArray, but I just recommend in this case to simply pass the data in a parameter:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
showWeather(JSON.parse(this.responseText));
}
};
xhttp.open("GET", "https://fcc-weather-api.glitch.me/api/current?lon=55&lat=12", true);
xhttp.send();
}
function showWeather(weatherArray) {
console.log(weatherArray);
}
loadDoc();
Ajax is asynchronous call, and you are printing data before invoking the ajax call,
I made some changes try it.
let weatherArray = [];
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
weatherArray = JSON.parse(this.responseText);
console.log(this.responseText);
}
};
xhttp.open("GET", "https://fcc-weather-api.glitch.me/api/current?lon=55&lat=12", true);
xhttp.send();
}
loadDoc();
/* Expecting the value to be stored and be shown in console*/
I'd like to provide an alternative modern approach using the Fetch api and Promises.
First fetch from the api
Convert it to json
Return the promise
Listen for the promise and log the result in the callback
function loadDoc() {
return fetch("https://fcc-weather-api.glitch.me/api/current?lon=55&lat=12")
.then(res => res.json())
}
loadDoc().then((weatherArray) => {
console.log(weatherArray);
})

Function returns undefined in Javascript [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
Can not figure it out how to return value (string) from this function:
function loadPage(url) {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", url, true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
//var html = xhttp.responseText
var html = document.documentElement.outerHTML;
return html
}
}
}
console.log(loadPage("http://stops.lt/vilnius/#trol/2/a-b"))
When I use console.log(html) inside xhttp.onreadystatechange it prints correct results, but I don't understand how to return loadPage(url). Tried both return xhttp.onreadystatechange and return xhttp.onreadystatechange() and none of these works.
Fuction loadPage is async, you need to use callback function(or Promise):
function loadPage(url, cb) {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", url, true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
//var html = xhttp.responseText
var html = document.documentElement.outerHTML;
cb(html);
}
}
}
loadPage("http://stops.lt/vilnius/#trol/2/a-b", function(html){
console.log(html);
});

Categories

Resources