jsonp Uncaught SyntaxError: Unexpected token : - javascript

i want see some game info on steam. I find a api, but when i use it say:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Also, I use jsonp but it is throw an error:
Uncaught SyntaxError: Unexpected token :
My code is below:
$.ajax({
//crossDomain: 'true',
url: 'http://store.steampowered.com/api/appdetails/?appids=730',
//url: 'http://api.steampowered.com/ISteamApps/GetAppList/v0001/',
//url:'http://store.steampowered.com/api/appdetails/?appids=730',
//url:'games.json',
type: 'get',
dataType:'jsonp',
//dataType:'json',
//data = JSON.parse(data);
crossDomain : true,
success:function(data){
console.log(data);
},
error:function(data){
console.log("Hata ",data);
}
});
I use anyorigin.com but it is not work. When I use local .json file working, but I need steam.

I don't think the URL you have in your example supports JSONP. I see this sort of JSON response:
{
"key": "value"
}
And for JSONP it needs to be:
callback({ key: value })
There might be some confusion here about what JSONP is. JSONP requires the API serve up raw javascript. Not only that, the server must serve up a particular function call in that javascript. JSONP is a hack around cross-origin policies.
edit:
As for solution, I would suggest you proxy the JSON through your own server-side application.

Related

Uncaught SyntaxError: Unexpected token < using Jsonp

Problem:
Uncaught SyntaxError: Unexpected token <
What I tried
Request: Jsonp
Response: returned XML Response 200.
Cross Domain Request that's why used data type: jsonp
Script code:
$.ajax({
url: "some url",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
type: "POST", /* or type:"GET" or type:"PUT" */
data:myusername,
crossDomain: true,
dataType: 'jsonp',
data: {
'name':myusername
},
success: function (result) {
console.log(result);
},
error: function () {
console.log("error");
}
//});
});
Here AJAX response is XML.
But can someone tell how can I solved unexpected token problem.
Response is XML.
solution i found is third party request
var urljson='cross-damin-url';
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' +
encodeURIComponent('select * from xml where url="' + urljson + '"') +
'&format=xml&callback=?';
$.getJSON(yql, function (data) {
console.log(data.results[0]);
});
Any suggestion is most welcome.
the problem is the line "dataType: 'jsonp'". Setting it this way the ajax call expect the result to be a jsonp (a json object wrapped as a params in a callback...) this is useful if you're doing a cross domain call (due to CORS). You have to set a "dataType: 'xml'"
Edit
considering the you have to do a CORS call, you have to change the output of the api, at least making something like
callbackName({value:'<your><xml>...</xml></your>'})
and parsing the xml from the string
"callbackName" is the name of a function or method declared in the page which make the ajax call and which will parse the json from the api... for instance something like:
function callbackName(result) {
console.log($.parseXML(result.value));
}
JSON and XML are arbitrarily nested data-interchange formats. You take a (well-formed) string and convert it to a data structure based on the rules of the format. Their similarities stop there.
So you can't just parse XML as JSON, they have different rules for turning a string (like that returned by an HTTP request) into a data structure. Which is why you're getting an error.
Parsing XML with an XML parser (like the one built into every browser) instead of a JSON parser will not throw an error.
But your actual problem is that it's a cross-domain resource and the browser (for good reason) won't let you. If you need a cross-domain resource and you don't control it and it doesn't have a CORS header you have a few options:
Beg the entity that controls the resource to add a CORS Header
Pipe the resource through your domain.
To expand on option 2:
Your page requests the resource from your webserver, your webserver makes an http request to the cross-origin resource, and then sends the result back to the browser.
About JSONP
JSONP was a hack invented before CORS to bypass the browser's security model. It was (meant) to be used by people who understood the risks, knew what they were doing and why. It involves potentially executing arbitrary third-party code on your page. Needless to say, that's bad.

Obtaining json from api with jquery ajax not working

I'm trying to obtain a json object from an api endpoint using jquery and ajax. This is my code:
$.ajax({
url: 'https://this-specific-website.com/customers.json',
type: 'GET',
contentType: 'application/json'
}).done((response)=> {
console.log('HELLLLLO INSIDE response')
console.log('response', response)
})
I also tried the same with the $.getJSON like this:
$.getJSON('https://this-specific-website.com/customers.json', (response)=> {
console.log('HELLO INSIDE response')
console.log('response', response)
})
but I keep getting the following error:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Is there a way to fix this issue?
Thank you in advance!!
UPDATE:
I finally did get it to work. Instead of using jquery and ajax on the front end, I created a seperate .js file and used http.get() like this:
Calling a JSON API with Node.js
Use JSONP in case your server supports this, below is the sample. ALternative is do a call to servelet or PHP in same domain which do a backend call and return you the response to your normal AJAX (or AJAX JSON_P)
$.ajax({
url:"testserver.php",
dataType: 'jsonp', // Notice! JSONP <-- P (lowercase)
success:function(json){
// do stuff with json (in this case an array)
alert("Success");
},
error:function(){
alert("Error");
}
});
You can not do a CORS request from the browser if the server you are requesting the JSON from does not have it enabled. You can try JSONP if they support that.
If you are running on a backend then you can do a server-to-server request and that should work.
For example if you are on a PHP server use:
<?php echo file_get_contents("https://this-specific-website.com/customers.json"); ?>

How to get JSON with jQuery from another domain

I have a little page and I need to get JSON from another domain. If make this:
$.get( "http://dev.frevend.com/json/users.json", function( data ) {
console.log(data);
alert( "Load was performed." );
});
I get an error. I understand why it throws this error, but I don`t know how to aviod it. I have not acces to the server.
XMLHttpRequest cannot load http://dev.frevend.com/json/users.json. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:3000' is therefore not allowed
access.
I also tried to use JSONP, but as I understand in that case server should wrap response with callback function, because I got a SyntaxError.
Is it possible to make this request with JSONP?
I tried
$.ajax({
url: "http://dev.frevend.com/json/users.json",
dataType: "jsonp",
jsonpCallback: "logResults"
});
function logResults(data) {
console.log(data);
}
But got
Uncaught SyntaxError: Unexpected token :
JSON is valid, I checked.
You need to allow access in your project configuration.
Below site has more information
http://enable-cors.org/server.html
Thanks,
Use JSONP in jquery for this purpose JSONP reference
Try to add a header into your PHP file which is responsible for executing every request.
header('Access-Control-Allow-Origin', '*');

Uncaught SyntaxError: Unexpected token : ajax call

So I'm trying to query the below json feed, however I keep getting the error in the topic.
I've searched around this site for possible answers however none that I've come across have worked so far. Commented out datatype and jsonp, jsonpCallback isnt it either, either is data, I've made sure that it validats via http://jsonformatter.curiousconcept.com/ and it does. I really dont know.
$.ajax({
type: 'GET',
url: 'http://raidbots.com/json/playerdata/us/mannoroth/usiris',
cache:true,
dataType: 'jsonp',
data: {
format: 'json',
},
success: ranks,
jsonpCallback:'callbackName',
error: function(data) { console.log(data); },
jsonp: false,
});
function callbackName(data){
console.log("jsonpCallback");
}
var ranks = function(data) {
console.log(data);
}
Thank you
-Art
The error is in your JSONp data because it's just JSON and not JSONp. JSONp requires the document to be valid JavaScript containing a function call.
If they don't support jsonp you need to use a proxy script (e.g. a php script on your server that retrieves the document) or ask them to send CORS headers so you can use a normal non-JSONp AJAX call to retrieve the data directly.

JSONP request returning error: "Uncaught SyntaxError: Unexpected token :"

So I'm trying to make a request to the Stack Exchange API with the following jQuery code:
$.ajax({
type: 'POST',
url: 'http://api.stackoverflow.com/1.1/stats',
dataType: 'jsonp',
success: function() { console.log('Success!'); },
error: function() { console.log('Uh Oh!'); }
});
But when I open the file on my machine, in either FireFox or Chrome, and make the request, I get this error:
Resource interpreted as Script but transferred with MIME type application/json.
Uncaught SyntaxError: Unexpected token :
Uh Oh!
I don't have a clue what's going on. I know the Stack Exchange API Gzips its responses, would this cause any trouble?
You have to set an unconventional parameter to get the SO API to work. Rather than the conventional callback, you need to pass a jsonp parameter.
Furthermore, you can't do POST with JSONP.
$.ajax({
type: 'GET',
url: 'http://api.stackoverflow.com/1.1/stats',
dataType: 'jsonp',
success: function() { console.log('Success!'); },
error: function() { console.log('Uh Oh!'); },
jsonp: 'jsonp'
});
It is not possible to do cross-domain AJAX using the conventional XMLHTTPRequest. This is for security reasons (it's call the same-origin policy).
There is a workaround. script tags are not subject to this restriction. This means that you can insert a script tag into the document that calls a URL. If you define a globally-accessible function in your script and tell the remote server what that function is called, the server can pass code that wraps the data to be sent in a call to that function.
The difficulty you had here is with the StackOverflow API. Conventionally, you would use the callback argument in your request, to tell the server what your function is called. However, StackOverflow's API asks you to use the jsonp parameter instead.
Try this URL: http://api.stackoverflow.com/1.1/stats?jsonp=callme
"callme" is the name of your callback function - in your GLOBAL NAMESPACE (window object).
By the way, if you are running Firefox and have the JSONView add-on installed you can test the above URL (and yours for comparison) directly.
Result from calling the URL:
callme({
"statistics": [
...
]
})

Categories

Resources