Getting "Unexpected end of JSON input at JSON.parse - javascript

Just getting a Syntax Error, "Unexpected end of JSON input at JSON.parse"
var trivia;
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var request = new XMLHttpRequest();
request.open('GET', 'https://opentdb.com/api.php?amount=5&category=15&difficulty=easy&type=boolean');
request.send();
trivia = JSON.parse(request.responseText);
console.log(trivia);

The problem is that you need to wait for the response to arrive before continuing on. You can achieve just that using the AJAX request's onload event:
var trivia;
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var request = new XMLHttpRequest();
request.open('GET', 'https://opentdb.com/api.php?amount=5&category=15&difficulty=easy&type=boolean');
request.onload = function() {
trivia = JSON.parse(request.responseText);
console.log(trivia);
}
request.send();

Related

How do you use API keys in HTTP Requests?

I am struggling to work out if there is a way to use an API key when trying to call data from an endpoint and if so, where would I put it?
var request = new XMLHttpRequest("Ocp-Apim-Subscription-Key: {KEY}")
// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'https://api.sportsdata.io/v3/mlb/scores/json/AreAnyGamesInProgress')
request.onload = function () {
// Begin accessing JSON data here
}
// Send request
request.send()
You need to put it in a HTTP request header most of the times.
var request = new XMLHttpRequest();
request.open('GET', 'https://api.sportsdata.io/v3/mlb/scores/json/AreAnyGamesInProgress');
request.setRequestHeader("Ocp-Apim-Subscription-Key", "{KEY}");
request.onload = function () {
//...
};
request.send();
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader

Reading JSON data from a url using javascript

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.

XMLHTTPRequest POST getting stuck

I am trying to POST to a google maps service. If you click on the URL you will see the JSON response that I am expecting to get
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest()
var url = "https://maps.googleapis.com/maps/api/directions/json?origin=Exeter&destination=Deal&region=uk&mode=driving"
xhr.open('POST', url, true)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
// do something to response
alert(this.responseText)
}
However, this code gets stops after xhr.onload = function(). So I never get the response back. Is there an error in my code?
You forgot to send the request.
xhr.send("The string of application/x-www-form-urlencoded data you are POSTING goes here");
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest()
var url = "https://maps.googleapis.com/maps/api/directions/json?origin=Exeter&destination=Deal&region=uk&mode=driving"
xhr.open('POST', url, true)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
// do something to response
alert(this.responseText)
}
xhr.send("data to be send");
Try this.

Parsing JSON url in pure javascript

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

Ionic controller XMLHttpRequest function doesn't work

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 ==.

Categories