I want to use AJAX and the SoundCloud API to get the tracks of a user.
jQuery.ajax({
url: 'http://api.soundcloud.com/resolve?url=http://soundcloud.com/[SOME USER]/tracks/&format=json&consumer_key=[MY KEY]&callback=?'
, dataType: 'jsonp'
, success: function( data ) {
console.log( data );
}
});
I can see that chrome gets the json data but I get the error
Uncaught SyntaxError: Unexpected token ILLEGAL
in the console.
The issue is probably that the json file is an json array. Could that be the error?
And if yes, how can I convert the array into single objects?
The problem is that the description field in track id #159500192 ('Summer Chords Pt. 2' (Electro House Mix)) has invisible characters that are not legal inside of JavaScript strings, so the JavaScript parser chokes when trying to the run the JSONP response as a script. SoundCloud should encode these values when serving content via JSONP.
Because SoundCloud supports CORS, you don't need to use JSONP at all. You can simply request the file directly, by removing the callback=? parameter and using dataType: json (not jsonp):
jQuery.ajax({ url: "https://api.soundcloud.com/resolve?url=http://soundcloud.com/[USER]/tracks/&format=json&consumer_key=[KEY]",
dataType: 'json',
success: function(d) { console.log(d); }
});
Related
I am developing i small app that displays some JSON data
inside of a listview. To receive the data I am using a simple request.
And I am getting always the same issue:
Uncaught SyntaxError: Unexpected token :
my code:
$.ajax({
url: 'http://localhost/documents.json',
data: {
format: 'json'
},
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
dataType: 'jsonp',
success: function(data) {
// do something with the data
},
type: 'GET'
});
});
My JSON file is valid. I checked it with a JSON validator.
Invalid JSON (no matter how mangled) cannot generate a JavaScript syntax error if you parse it with JSON.parse() or any decent dedicated parser (and that's what jQuery does). The same happens with all other standard data types (XML, HTML, plain text...). All symptoms suggest you're expecting JSONP but getting some other data type. The builtin browser network pane should reveal what you're getting exactly.
Whatever, if you only want JSON and nothing but JSON you should simplify your code as follows:
Omit protocol and host:
url: 'http://localhost/documents.json',
should be:
url: '/documents.json',
(Probably not required, but will help to void errors.)
Ask for the correct data type:
dataType: 'jsonp',
should be:
dataType: 'json',
Do not parse again what jQuery already parsed for you:
var json = $.parseJSON(data);
should be:
var json = data; // Yeah, nothing :)
This should be enough for local AJAX. If you really need a cross-site request (I asked twice and never got an answer) you have to tweak your server to either return the appropriate CORS headers or implement JSONP data type and change your client-side code accordingly because you'll no longer have JSON—because JSONP is not JSON!
Check if your json is valid by using jsonlint.com or you can use jsonmate.com. These are very helpful to me when I'm debugging json.
Also - it would help to have a link to the full code. Use jsfiddle.net to put your code into - then link it to this post. This will help the community debug your code.
I'm very new to JSON and JSONP.
I've read through each of the posts that are recommend by the SO search for this error, but I can't seem to get a handle on it.
I have the following code to grab data from an EXTERNAL website:
$.ajax({
url: "https://url.com/authenticate?login=test&apiKey=test",
dataType: 'jsonp',
success:function(json){
console.log("login successful");
}
});
When I load the page, I get:
Uncaught SyntaxError: Unexpected token :
and when I click on the error in Chrome, I see
{"Status":{"Code":"2","Message":"Authentication Succeeded","Success":"true"}}
with a little red x after "true"})
From this, it seems as though I have succeeded in logging in, but I'm doing something else wrong because my console.log("login successful"); never fires. What am I doing wrong?
P.S.
I've tried dataType: 'json' but I get the No 'Access-Control-Allow-Origin' header is present as I'm on a different server, so I went back to jsonP as this is cross-domain.
I've also tried the above url as url: "https://url.com/authenticate?login=test&apiKey=test&callback=?", as I've read I need a callback, but I don't really understand what the functionality of callback is and either way, the error that gets returned (whether &callback=? is in there or not) is:
authenticateUser?login=test&apiKey=test&callback=jQuery111107732549801003188_1423867185396…:1 Uncaught SyntaxError: Unexpected token :
so it's adding the callback in either way....
Also, from the API I'm trying to access:
"this uses the REST protocol, and provides data structured as XML or JSON"
This is not a duplicate of the linked post as the information in the linked post does a great job of explaining what JSONP is, but doesn't answer my specific question regarding why I get data back (so my call is successful,) but why I still get an error and cause my script to stop.
The API you're sending the AJAX request doesn't implement JSONP. It ignores the callback= parameter, and just returns ordinary JSON. But when the browser tries to process this as JSONP, it gets a syntax error because it's not properly formatted. JSONP is a JSON object wrapped in a call to the specified callback function, e.g. it should be sending back:
jQuery111107732549801003188_1423867185396({...});
where {...} is the JSON object you're trying to retrieve. But it's just returning {...}.
You should implement this using a PHP script on your own server. It can be as simple as this:
<?php
$username = urlencode($_POST['user']);
readfile("https://url.com/authenticate?login=$username&apiKey=test");
Then your AJAX call would be:
$.ajax({
url: "yourscript.php",
type: "post",
dataType: "json",
data: { user: "test" },
success: function(json) {
console.log("login successful");
}
});
I'm using $.ajax to get JSON data from a REST API.
The problem is that the responseText I get is malformed so I get SyntaxError: JSON.parse: unexpected non-whitespace character error.
I found out that the problem is that the responseText is something like this:
"433
{"Result":{"Locale":"us","ServiceId":1111,"Name":"name",
"HDLevel":"HD Level
5a0
Unknown","Category":"News","Subcategory":"ne
5b0
ws"}
}"
...
so it can't be parsed correctly to JSON.
I think I need a way to delete all those strings (433, 5a0, 5b0) and also delete new line characters.
But I think I need a general way to delete those strings because there are more like them in my responseText and I can't know all names.
Any ideas on how I can do that and obtain a correct JSON?
Thanks
edit:
the service uses JSON as format of the returned data and I'm using:
$.ajax({
type: 'GET',
url: URL,
dataType: 'json',
success: function(obj) {
},
error: function( jqXHR, textStatus, errorThrown ) {
},
});
I can't access the service server side so I can't edit any php or other languages issues.
Seems to me more like an unexpected http transfer encoding (chunked). Your actual JSON data is probably fine. Take a look at this question: jquery support Transfer-Encoding:chunked? how
I am trying to retrieve data from a web service using an ajax call. The call is succeeding, because I am able to successfully print the data in the console using console.log(). However when I attempt to take my data, and convert from a string into an array, the code fails. I am currently trying to use eval, but have also tried to use JSON.parse. Both fail with an error of Uncaught SyntaxError: Unexpected identifier. Any ideas on how to get around this?
$.ajax({
type: "POST",
url: (redacted)
data: (redacted)
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log(response.d);
var data = eval("[" + response.d + "]");
This is where my code fails. Like I said, console.log(response.d) works, with an output simlilar to this: { 'code':'1234', 'description':'Record 1'}, { 'code':'1234', 'description':'Record 2'}, { 'code':'1234', 'description':'Record 3'}
Is my problem the use of eval? Any input would be greatly appreciated
First, I would use JSON.parse() here instead of eval for decoding JSON strings.
However in this case I believe the return data has already been decoded by jQuery. console.log(response.d) returns a nice looking object and not a "{...}...." string correct?
I am trying to access data from a php server with a cross domain support. So when i try $.ajax with dataType : 'jsonp' i have an error in console: Uncaught SyntaxError: Unexpected token The file is interpret as a javascript file an the request fail. Have you an idea for get data whithout this error.
$.ajax({
url : 'http://domaine.com/json.php',
contentType: "application/json; charset=utf-8",
dataType : 'jsonp',
success : function(data){
console.log(data);
// no enter in this callback
},
complete: function(data1, data2, data3){
// no data from file.js
}
});
First make sure that your PHP script supports JSONP. Identify the query string parameter that needs to be passed so that the script returns JSONP. Then test it in your browser by directly entering the following address in your address bar:
http://domain.com/json.php?callback=abc
You should see something along the lines of:
abc({ ... some JSON here ... })
You might need to adjust the callback name parameter if your PHP script expects a different one. This could be the case if you see the following output ({ ... some JSON here ... } without being wrapped in your javascript function)
And once you have ensured that you have a valid PHP script that returns JSONP you could consume it:
$.ajax({
url : 'http://domain.com/json.php',
jsonp: 'callback',
dataType : 'jsonp',
success : function(data){
console.log(data);
// no enter in this callback
},
complete: function(data1, data2, data3){
// no data from file.js
}
});
Things to notice:
I have specified the callback using the jsonp: 'callback' parameter
I have gotten rid of the contentType: 'application/json' parameter because jQuery's implementation of JSONP uses script tags which doesn't allow you to set any request headers.
You need to add ?callback=? to the request so that the proper callback is evaluated. It may not be called callback, though. You need to find out what it is called from the domain.
If the domain (and browser) supports CORS, you don't even need to use JSONP. You can use a normal request.