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

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!

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"

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

<!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

mimicing jsonp in javascript

<script>
window.addEventListener('load',function(){
var unique_code="3412313ad"// Initialize it with the unique code provided to you.
var param1="1"; // Initialize this with the value that you wish to see.For example 1 for navbar display , 2 for the side floating pop up
//while 3 for a transparent overlay on the whole page.
var domain=window.location.hostname;// current domain.
function jsonp(url, callback) {
var callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random());
window[callbackName] = function(data) {
delete window[callbackName];
document.body.removeChild(script);
callback(data);
};
var script = document.createElement('script');
script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName;
document.body.appendChild(script);
script.onerror=function(){
alert("failed to load snippet!");
}
}
jsonp('http://localhost/server.php?unique_code='+unique_code+'&domain='+domain, function(data) {
alert(data);
if(data.status=='success'){
alert('success');
}else alert(data.reason);
});
});
</script>
This is a code that mimics jsonp of the jquery to get a script from the remote server.
I used the answer given in this question JavaScript XMLHttpRequest using JsonP
Server side code would be
if(isset($_GET['unique_code']) && !empty($_GET['unique_code']) && isset($_GET['domain']) && !empty($_GET['domain'])){
$unique_code=$_GET['unique_code'];
$domain=$_GET['domain'];
$statement=$mysqli->prepare('select * from `snippet_users` where unique_code=? AND domain=?');
$statement->bind_param('ss',$unique_code,$domain);
if(!$statement->execute())
die(json_encode(array('status'=>'error','reason'=>'Server error.')));
$result=$statement->get_result();
if(mysqli_num_rows($result)>0)
die (json_encode(array('status'=>'success')));
else die(json_encode(array('status'=>'error','reason'=>'Unique code/Domain error.')));
}else{
die(json_encode(array('status'=>'error','reason'=>'Unique code/Domain error.')));
}
Everything is working perfectly fine but i see error in the console , somewhat like this :
What would be my solution so that i dont get this error as well as i get my data in the alert box?
You are outputting application/json instead of application/javascript, so your browser thinks it's not valid. The json should be in a function call (callback parameter). The callback parameter should be validated on the server side however to prevent xss injection:
Is it necessary to validate or escape the jsonp callback string

"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

HTML page will not complete an XMLHTTPRequest

So I'm trying to get an outside script to complete a login request using XMLHTTPRequest.
The error I'm getting is XMLHttpRequest cannot load http:///.php. Origin http://* is not allowed by Access-Control-Allow-Origin.
Now I've grown quite familiar with this post:
XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin
And from what I understand I need to request it as a JSONP object. The problem with that, is I'm using an XMLHTTPRequest and cannot use the jQuery library to do that.
Here's my code from the html page I'm trying to execute the script from:
<html>
<head>
<meta http-equiv="Access-Control-Allow-Origin" content="*">
<script language = "javascript" type="text/javascript" src="jquery-1.7.2.js">
</script>
<script language = "javascript" type="text/javascript" src="main.js">
</script>
<script type="text/javascript">
function show_prompt()
{
var name=prompt("User Name");
var password =prompt("Password");
var loginWorked = false;
if (name!=null && name!="") loginWorked = init(name,password);
if(loginWorked == true){
window.location = "Toolbar.html"
}
}
</script>
</head>
<body>
<input type="button" onclick="show_prompt()" value="Login" />
</body>
</html>
And the code from my main file:
The init function:
function init(username,password){
//Initializes the toolbar.
init.user = username;
init.pass = password;
init.pass_hashed = sha256(init.pass);
var key = fetchKey(username);
init.pass_hashed += key;
init.pass_hashed = sha256(init.pass_hashed);
var loginParams = "login=1&pwd=" + init.pass_hashed + "&uname=" + init.user + "&LastKey=" + getKey();
loginReqReturn = send_request("http://data.nova-initia.com/login2.php","POST", loginParams);
if(loginReqReturn.responseText != "Error: Login Incorrect "){
return true;
}
else return false;
}
And the sendRequest method:
function send_request(theURL, theMethod, theParams)
{
var theReq = new XMLHttpRequest();
theReq.overrideMimeType("application/json");
theReq.open(theMethod,theURL,false);
if(typeof(theParams) === "string")
{
theReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
}
else
{
theReq.setRequestHeader("Content-type", "application/json");
theParams = JSON.stringify(theParams);
}
if(_key) theReq.setRequestHeader("X-NOVA-INITIA-LASTKEY", _key);
if(theParams)
{
theReq.send(theParams);
}
setKey(theReq);
return theReq;
}
Not the most efficient code, but it at least works when I execute it in a non-HTML context (I'm working on a toolbar for Google Chrome, but need the html overlay to work). Any help is much appreciated.
I'm not sure what your exact question is, but if you know that using JSONP is the solution that you can do that without using jQuery. Here's how it works: http://en.wikipedia.org/wiki/JSONP
If this is for a Google Chrome Extension, you can request permissions for cross-origin XMLHttpRequest requests within the extension's manifest:
{
...
"permissions": [
"http://data.nova-initia.com/"
],
...
}

Categories