does somebody know why this doesn't work? I get a error message at 'request.status' in Ionic
.factory('Nieuws', function() {
var url = "http://echo.jsontest.com/ID/2/bericht/test";
var request = new XMLHttpRequest();
request.open("GET", url);
var nieuws;
request.onload = function () {
if (request.status = 200) {
nieuws = JSON.parse(request.responseText);
//console.log(nieuws);
}
};
You're trying to assign a value to a read only property when you need to be making a comparison.
Replace = with ==.
Related
I'm not that experienced when it comes to APIs so excuse me in advance.
I'm trying to get a button to display the contents (response) of an API, and the code below works wonders. I'm wondering how I would make the exact same request, but instead of the "explicit" endpoint, I want a "history" endpoint instead.
How would I do this?
const data = null;
const xhr = new XMLHttpRequest();
xhr.withCredentials = true;
var object1;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
object1 = JSON.parse(this.responseText);
}
document.getElementById('thejoke').innerHTML = object1.value;
});
xhr.open("GET", "https://api.chucknorris.io/jokes/random?category=explicit");
xhr.send(data);
The simplest answer would be to make it a function:
function send(category) {
const url = "https://api.chucknorris.io/jokes/random?category=" + category
const data = null;
const xhr = new XMLHttpRequest();
xhr.withCredentials = true;
var object1;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
object1 = JSON.parse(this.responseText);
}
document.getElementById('thejoke').innerHTML = object1.value;
});
xhr.open("GET", "");
xhr.send(data);
}
And then you can you call it like this:
send("explicit");
The only problem you then face is that object1 is not available outside of the function. You could work around this by making object1 a global variable, or do the things you want to directly in the EventListener.
I want to read data from this link http://starlord.hackerearth.com/gamesext.
I went through this https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON and was able to obtain data from https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json.
Trying similar approach for getting data from http://starlord.hackerearth.com/gamesext is not working for me.
This is how I tried:
var requestURL = 'http://starlord.hackerearth.com/gamesext';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function() {
var games = request.response;
document.getElementById("para").innerHTML = "for check";//para is a paragraph id
fun1(games);
}
function fun1(jsonObj){
//getting first title
document.getElementById("para").innerHTML = jsonObj[0]["title"];
}
I would want to know is that data in JSON and how to get it?
Try using the JSON.parse() method:
function fun1(jsonObj){
//getting first title
jsonObj = JSON.parse(jsonObj);
document.getElementById("para").innerHTML = jsonObj[0]["title"];
}
This will turn valid JSON into a javascript object that can be accessed as you are trying to do below.
This works perfectly fine for me:
var requestURL = 'http://starlord.hackerearth.com/gamesext';
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(xhttp.response[0].title) # LittleBigPlanet PS Vita
}
};
xhttp.open("GET", requestURL);
xhttp.responseType = 'json';
xhttp.send();
Give it a try!
Using fetch this is pretty simply.
Below is an example.
const url = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';
async function getData() {
const json = await (await fetch(url)).json();
console.log(json);
}
getData();
just put request.send(); after all the code you provided.
I am very new to JS, trying to create simple page which does next:
takes IP of some server
then sends a get request to this server
parses get response,
adds filtered lines to the table on html page.
I was able to do all the steps through the browser console but when, moving to the JS file with get function for some reason function does not return value.
In below code snip line 6 will print undefined in the console.
Any idea how to return "statuses" from the function getStatus?
Should it be some timeout between line 5 and 6?
Thanks!
$("input[type='text']").keypress(function(event){
if(event.which === 13){
var address = $(this).val();
var urlStat = 'http://'+address+':666/bla?open=stats';
var status = getStatus(urlStat);
console.log(status);
$("input[type='text']").val('');
$('table').append("<tr><th>"+address+"</th><th><ul></ul></th><th></th></tr>");
}
});
function getStatus(url){
var xhr = new XMLHttpRequest;
xhr.open("GET", url);
xhr.send();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var regexStatus = /(\w+ state:.*?)</g
var response = xhr.responseText;
var statuses = response.match(regexStatus);
console.log('Inside function getStatus'+statuses);
return statuses;
};
}
};
The problem with your code is that the status is returned after your your request has been sent. That gives a small delay. Because you immediatly ask for the return value of getStatus, you will get undefined.
You could solve this problem with a callback function:
function getStatus(url,callback){
var xhr = new XMLHttpRequest;
xhr.open("GET", url);
xhr.send();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var regexStatus = /(\w+ state:.*?)</g
var response = xhr.responseText;
var statuses = response.match(regexStatus);
console.log('Inside function getStatus'+statuses);
if(callback) callback(statuses);
};
}
};
You call the getStatus function with a function, which is called after you got a response from you request.
E.g:
getStatus(url,function(statuses){
console.log(statuses);
});
EDIT
For a better and longer explanation, consider to check out How do I return the response from an asynchronous call?
I'm trying to parse a url in pure javascript, just one executable file.
url = 'http://myurl.php?format=json'
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
var mystuff = JSON.parse(request.responseText);
} else {
// some error
}
};
request.onerror = function() {
// some error
};
request.send();
console.log(mystuff);
When I do this, I get a XMLHttpRequest is not defined error. What's the best way to do this, the simplest way?
Thank you.
This statement is wrong you should url as a variable not "url" as a string,
request.open('GET', 'url', true);
to
request.open('GET', url, true);
Furthermore the xmlHttpRequest works only on some versions of browsers.
You could do something like this to check whether xmlhttpRequest works on your browser,
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
Is it possible to read binary file from url?
var url = 'http://example.com/image/abc.jpg';
var reader= new FileReader();
reader.addEventListener('load', function () {
// whatever
});
reader.readAsArrayBuffer(url);
Above example is not working (url is not a object).
var file = new File([""], "url");
is empty
You have to use HTTP GET to get the file. Maybe this is what you need?
function httpGetAsync(theUrl, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.response);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
httpGetAsync("http://cdn.androidbeat.com/wp-content/uploads/2015/12/google-logo.jpg", res => console.log(res))
URL in your case is a string object. You need to use HTTP get in this case. HTTP GET request in JavaScript? and read the response.