how to grab JSON Data from url using JavaScript? (new to JSON) - javascript

<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript - read JSON from URL</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<script>
function setup() {
loadJSON("https://www.westelm.com/services/catalog/v4/category/shop/new/all-new/index.json", gotData, 'jsonp');
}
function gotData(data){
alert(data);
}
</script>
</body>
</html>
I am new to the developer role, please help. First it kept giving me Access denial to the url ERROR!. Then i learned about jsonp and added it. Now i don't see anything showing up, when i should be getting the json data. !JSON data from the url is correct ran it in JSONLINT!

var xmlhttp = new XMLHttpRequest();
var url = "https://www.westelm.com/services/catalog/v4/category/shop/new/all-new/index.json";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
console.log(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
That code will normally work, but for this you should be getting this error:
Failed to load
https://www.westelm.com/services/catalog/v4/category/shop/new/all-
new/index.json: No 'Access-Control-Allow-Origin' header is present on
the requested resource. Origin 'null' is therefore not allowed access.
The response had HTTP status code 403.
That's because this server doesn't allow JSON Reqs, and will not allow you access. You could try using CORS (https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) but I'm not sure how much that will help you

Related

API data prints to console in node but doesn't display in html

My goal is to do a simple get request and display the data to an HTML page.
So first I set up the request in node.js to test it. With node, the data showed up correctly when I ran it with console.log(response).
The problem comes when I try to display the data to the page. Basically, nothing shows up when I try document.getElementByID('demo').innerHTML = response;
I even tried to just use an alert but to no avail.
I am obviously doing something wrong but I am not familiar enough with JavaScript to know.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="demo"></p>
<script>
//causes error in html. Required for node.
// var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var HttpClient = function() {
this.get = function(aUrl, aCallback) {
var anHttpRequest = new XMLHttpRequest();
anHttpRequest.onreadystatechange = function() {
if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
aCallback(anHttpRequest.responseText);
}
anHttpRequest.open( "GET", aUrl, true );
anHttpRequest.send( null );
}
}
var theURL = 'https://XXXXXX..';
var client = new HttpClient();
let thisReply = null;
client.get(theURL, function(response) {
// var response1 = JSON.parse(response);
// alert(response1);
// console.log(response);
document.getElementById('demo').innerHTML = response;
});
</script>
</body>
</html>
Assuming this is not an issue with the document not finding the element you are looking for, you could try .innerText = response or wrapping your innerHTML elem in some HTML element: <p>${response}</p> I would be sure to also log out that element in addition to the api response to be sure you're grabbing the right thing.
#PrerakSola and #Abdullah Danyal answered the question in the main post comments.
"I checked that and I saw a console error that said Access to XMLHttpRequest at 'APILINK' from origin 'http://...' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource"
ANSWER: "You need to enable CORS on your API server. If you are using node along with express, refer to : expressjs.com/en/resources/middleware/cors.html"

SoundCloud API gives "Uncaught SyntaxError: Unexpected token : " error

In the console it's giving me the error "Uncaught SyntaxError: Unexpected token : ", but if I access direct SoundCloud URL in my browser then it's giving valid JSON. Earlier this code was working fine and today this issue started.
<html>
<head>
<script src="https://api.soundcloud.com/resolve.json?url=https://api.soundcloud.com/tracks/251912676/?secret_token=s-EkyTy&client_id=08f79801a998c381762ec5b15e4914d5"></script>
</head>
<body>
<h2>hellooo</h2>
</body>
</html>
Update:
Below is the actual code for which I am asking the question, above html I just created for example.
SoundCloud.prototype._jsonp = function (url, callback) {
var target = document.getElementsByTagName('script')[0] || document.head;
var script = document.createElement('script');
var id = 'jsonp_callback_' + Math.round(100000 * Math.random());
window[id] = function (data) {
if (script.parentNode) {
script.parentNode.removeChild(script);
}
window[id] = function () {};
callback(data);
};
script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + id;
target.parentNode.insertBefore(script, target);
};
I got the reason of issue, earlier soundcloud were responding response in jsonp but now they are providing JSON even I passed JsonP callback function. I had to make ajax request to fix it.
I used following code to fix it.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callback( JSON.parse(this.responseText) );
}
};
xhttp.open("GET", url, true);
xhttp.send();
The following script tag expects JavaScript code in the source and not JSON.
<script src="file.js"></script>
I suppose that you want to use this externally produced json...
A way to "get" it is using an asynchronous ajax request like $.get(url,callback);
Calling it as a script will sure fail...
Because it's not a script.
Try to run the snippet!
var url = "https://api.soundcloud.com/resolve.json?url=https://api.soundcloud.com/tracks/251912676/?secret_token=s-EkyTy&client_id=08f79801a998c381762ec5b15e4914d5"
var json;
$.get(url,function(result){
json = result;
// show in console
console.log(JSON.stringify(json));
// Now using it...
$("#json_usage").html(json.tag_list+" and all the "+json.permalink);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<!--script src="https://api.soundcloud.com/resolve.json?url=https://api.soundcloud.com/tracks/251912676/?secret_token=s-EkyTy&client_id=08f79801a998c381762ec5b15e4914d5"></script-->
</head>
<body>
<h2>hellooo <span id="json_usage"></span> !</h2>
</body>
</html>
In the above, the resulting json is placed in the json variable and then console logged.
Sorry you've been having trouble with JSONP responses from the SoundCloud API. This was due to a bug that made it into production in the last few days. We've just deployed a fix, and so this endpoint will now be returning valid JSONP responses rather than just JSON, if you specify a callback parameter. Sorry for the confusion!

"Unexpected end of input" of the doctype tag when running AJAX asynchronous but not when synchronous

I've got this project where I get the error Uncaught SyntaxError: Unexpected end of input on line 1 of my HTML code, which is the DOCTYPE tag. I don't know how to fix this since the tag doesn't have a closing tag.. I only get this error when running the AJAX asynchronous, which I must do or the AJAX just gets stuck in an infinite loop manner.. I'm using this to interact with an API that grabs all the red days of a calendar year. Any ideas on how I fix this? I've been searching for an answer but I haven't found any that matches my problem.
Here's my AJAX code:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://api.dryg.net/dagar/v2/' + year, true);
xhr.send();
var json = JSON.parse(xhr.responseText);
for (item in json.dagar) {
var propertyObject = json.dagar[item];
for (subitem in propertyObject) {
if (subitem === 'röd dag') {
var redDay = propertyObject[subitem];
if (redDay === 'Ja') {
calendar.markRedDays(propertyObject.datum);
break;
}
}
}
}
And this is the HTML:
<!DOCTYPE html> <--- This is where the error points to
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Online Calender</title>
<script src='https://cdn.firebase.com/js/client/1.1.1/firebase.js'></script>
<link href='http://fonts.googleapis.com/css?family=Port+Lligat+Sans' rel='stylesheet' type='text/css'>
<link rel='stylesheet' type='text/css' href='style.css'>
</head>
<body>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
<script src="firebase1.js"></script>
</body>
</html>
It appears that the response (xhr.responseText) is empty because the request is ascynchronous (it has not been received yet).
The method that throws that exception is JSON.parse.
A callback should be registered (as noted in the first comment on your question) to handle the response.
Please note that you should handle the case when the reposone is not JSON. For example, it may be an html page saying the an error has occured.
Good Luck
Ok, the truth is you need to learn how AJAX works and read the docs I linked in the comments.
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://api.dryg.net/dagar/v2/' + year, true);
xhr.httpRequest.onreadystatechange = callbackFunction;
xhr.send();
alert("this alert is triggered after the request was sent but before it returned")
Now the request is sent, and it will eventually return, but your code will keep on running through the normal flow. Once the request returns it will trigger the "onreadystatechange" event. Thanks to the line I added above this will call your callbackFunction. This should look as follows:
var callbackFunction = function(){
// This is the state when the xhr request has returned, see the docs
if (xhr.readyState === 4) {
// This means there was no error.
if (xhr.status === 200) {
//Here you can access the response of the xhr
var json = JSON.parse(xhr.responseText);
for (item in json.dagar) {
var propertyObject = json.dagar[item];
for (subitem in propertyObject) {
if (subitem === 'röd dag') {
var redDay = propertyObject[subitem];
if (redDay === 'Ja') {
calendar.markRedDays(propertyObject.datum);
break;
}
}
}
}
} else {
alert('There was a problem with the request.');
}
}
If it's still unclear look at the example on the MDN docs page

Having trouble parsing a JSON http request [duplicate]

This question already has answers here:
Ways to circumvent the same-origin policy
(8 answers)
Closed 8 years ago.
I referenced code from tutorials on w3schools.com. I don't know what I could be doing wrong, but when I test the site, I get no output. None whatsoever. I'll post the code below.
<!DOCTYPE html>
<html>
<body>
<p id="par1"></p>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://xproshowcasex.api.channel.livestream.com/2.0/livestatus.json?callback=status";
xmlhttp.onreadystatechange=function() {
//readyState 4: request finished and response is ready
//status 200: "OK"
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
//var 'url' is defined above
xmlhttp.open("GET", url, true);
xmlhttp.send();
function status(response) {
var arr = JSON.parse(response);
if (arr.isLive = true) {
document.getElementById("par1").innerHTML = "live";
} else {
document.getElementById("par1").innerHTML = "offline";
}
}
</script>
</body>
</html>
I checked the console log on chrome and is gave me this error:
XMLHttpRequest cannot load http://xproshowcasex.api.channel.livestream.com/2.0/livestatus.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
I have looked on the forums for livestream as well as other places and no one can offer me a solid solution. Hopefully someone here can. Thanks for the help!
--Edit--
I have searched this site and have not found a solution for my problem. If anyone knows where there may be a solution, please post a link, but as far as I know, there is none. As we all know, different code has different problems, so i would appreciate an answer rather than a [Duplicate] marking.
<!DOCTYPE html>
<html>
<head>
<meat charset="utf-8">
<title>test</title>
<script src="https://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script>
<!--Livestream status script-->
<!-- CAN BE PLACED IN BODY -->
<script type="text/javascript">
$(document).ready(function () {
function getCrossDomainJson(url, callback) {
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?callback=?",
data: {
q: 'select * from xml where url="' + url + '"',
format: "json"
},
dataType: "jsonp",
success: callback
});
}
/*INSERT STREAM NAME INBETWEEN 'x' eg. http://xSTREAMNAMEx.channel-api.livestream-api.com/2.0/getstream*/
getCrossDomainJson("http://xhellgateospreyx.channel-api.livestream-api.com/2.0/getstream", function(data) {
console.dir(data);
if (data && data.query && data.query.results && data.query.results.channel) {
var statusTest = data.query.results.channel.isLive;
if (statusTest == "true") {
document.getElementById("par1").innerHTML = "online";
}
else {
document.getElementById("par2").innerHTML = "offline";
}
}
});
});
</script>
<!-- end of script -->
<body>
//par1 will change to online if stream is online; par2 will remain as unaffected
//par2 will change to offline if stream is offline; par1 will remain as unaffected
//I separated the p tags for testing purposes, but they can be combined
//if you do so, change the id in the if/else statements
<p id="par1">unaffected</p>
<p id="par2">unaffected</p>
</body>
</html>
If you want more than one stream status, select the code from 'getCrossDomainJson' down to the first '});' and paste in between the two '});' and replace the stream name and the tag in 'getElementById'. Thanks to everyone who helped me with this problem! Hope this helps someone else.

xmlhttprequest GET in javascript does not give response

I am trying to consume the weather web service provided by wsf.cdyne.com/WeatherWS/Weather.asmx. I am sure that I can get a response in XML format by using the uri " 'http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityForecastByZIP?ZIP=' + zipcode".
So what I want to do now is sending the uri above using XmlHttpRequest. I added some alerts to monitor the status. After open() the readyState is 1. After that I can't get any other response. If I remove the statement "xmlHttpRequest.onreadystatechange = processRequest;", I cannot see any response after send(). So I just hope someone can help me to check what is wrong.
<html>
<head>
<title>weather app</title>
</head>
<body>
<script language="JavaScript">
function httpGet()
{
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
if (xmlHttp.overrideMimeType)
xmlHttp.overrideMimeType('text/xml');
}
else if (window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
}
}
}
xmlHttp.open( "GET", "http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityForecastByZIP?ZIP=85281", false );
alert("1 " +xmlHttp.readyState);
xmlHttpRequest.onreadystatechange = processRequest;
alert("2 " +xmlHttp.readyState);
xmlHttp.send();
alert("3 " +xmlHttp.readyState);
document.write(xmlHttp.responseText);
return xmlHttp.responseText;
}
httpGet();
</script>
</body>
</html>
As correctly stated by #robertklep this request is cross-domain. Browsers disallow cross-browser requests as a security measure so you don't hijack the user's sessions on their sites etc.
To get it to work you can create a proxy on the local site. If the site offers support to use JSONP cross-domain, you could use that.
For more information lookup some information on cross-domain policies or if they have some API docs, they may have information there on your problem too.

Categories