Uncaught SyntaxError: Unexpected token < using Jsonp - javascript

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.

Related

jsonp Uncaught SyntaxError: Unexpected token :

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.

Ajax calls to a CORS disabled service

Is it possible to use javascript to consume data from a webservice that is CORS disabled, only returns XML data (no option for json/jsonp) and over HTTPS? I do not have control of this webservice to make changes.
At best, if I run the following ajax I'll see an xml response getting sent back (using Chrome's developer tools) however my success function isn't being hit and I'll end up with an exception 'Unexpected syntax <' because it's anticipating a json padded response.
If I change dataType to just 'xml' I will get an error "Access-Control-Allow-Origin" not found in header response. Which is what I'd except since they have not enabled CORS.
$.ajax({
url: 'https://' + myURL + querystring,
username: usr,
password: pwd,
dataType:'jsonp text xml',
type: 'GET',
success: function (data) {
console.log( "success" );
},
cache: false,
contentType: false,
processData: false
});
Not directly.
You can write your own webservice that interacts with it and then access your service from JavaScript instead.
You have mentioned that , when used dataType jsonp,i would get the response.I guess that the webservice support jsonp,otherwise,the $.ajax couldn't get the response text.And then, you mentioned:
'Unexpected syntax <' because it's anticipating a json padded response
The dateType of jsonp in jquery will force the response text to be transformed from plain text to json object,but unfortunately the response text is returned in format of XML.
Since the webservice support jsonp and the jquery require jsonp must be return in json format, why not use the native javascript to resolve it?
function parseXml(xml) {
console.log('the return xml ',xml);
}
document.write('<script type="text/javascript" src="https://xxxx?param=xx&callback=parseXml"><\/script>');
At last,please don't reduce my marks now,its number has nearly been down to zero for this qustion.

Getting a parseerror from jQuery $.ajax post return using jsonp from Trakt.tv api

Working with the Trakt.tv API. It looks like I'm sending valid json as I'm able to authenticate but the return I receive is a parse error.
Resource interpreted as Script but transferred with MIME type text/html:
http://api.trakt.tv/recommendations/shows/myApiKeyCompleteNumbers?callback=jQuery111000155555475132972_1397674204444&{%22username%22:%22userName%22,%22password%22:%22mySha1PassComplete%22}&_=1397674207093
Uncaught SyntaxError: Unexpected identifier
The return says:
Disallowed Key Characters.
I'm using:
jQuery 1.11.0
Thanks in advance for any help or guidance
$(document).ready(function () {
function success(data) {
alert('data: ' + data);
}
var traktUser = 'myUserName';
var traktHash = 'mySha1Password';
var traktApi = 'myApiKey';
var data = {
'username': traktUser,
'password': traktHash
};
var postData = JSON.stringify(data);
var apiUrl = 'http://api.trakt.tv/recommendations/shows/' + traktApi;
$.ajax({
type: 'POST',
url: apiUrl,
data: postData,
contentType: 'application/json',
dataType: 'jsonp',
}).
done(success);
}); //document ready
You can't make a POST request using JSONP, jQuery is ignoring the POST instruction and making a GET request.
Your data is being placed in the query string and is not properly URL Encoded.
The server is responding with an HTML document containing an error message instead of a JavaScript script formatted according to JSONP rules.
It looks like the API you are trying to use does not support JSONP at all. Since you are passing your own user credentials in the request, this makes sense. JSONP is a hack to work around the Same Origin Policy that is implemented by browsers (these days we can use CORS instead) and there is no point in using it unless you want end user browsers to access the API directly. Since end user browsers couldn't access it without being given your username and password, it doesn't seem likely to be intended to be used that way.
Process the data from the API on your server instead.

Cross-Domain AJAX to Read XML

Noobie here. I'm writing a client script that needs to read an XML file from another domain. I tried using JSONP. I get a 200 response but the client can't access the returned data for some reason. I get two errors:
Resource interpreted as Script but transferred with MIME type text/xml
and
Uncaught SyntaxError: Unexpected token <
Here's the code (I've removed the XML url since it's confidential):
$(document).ready(function() {
$.getJSON("urlOfFilecallback=?", function(data) {
console.log(data)
})
});
When I try to render the data in the console I get:
ReferenceError: data is not defined
How can I fix this? Do I need to use a proxy?
You don't have to write your own proxy. You can use YQL if you want to here is an example how:
//sample site that returns xml
site = 'http://goo.gl/9iQWyG';
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from xml where url="' + site + '"') + '&format=xml&callback=?';
// Request that YSQL string, and run a callback function.
// Pass a defined function to prevent cache-busting.
$.getJSON(yql, function(data){
console.log(data.results[0]);
});
here is the jsfiddle check console.log.
(Usage limits of the public YQL API is 2,000 requests/hour per IP)
XML is not allowed for cross-domain requests by default.
However, with a little server-side programming you can create a proxy and load the data within your own domain, and output it as XML.
for more information see this Question
If you have access to the other domain side, you could also use this approach Cross Domain Request

"Security Err: Dom Exception" thrown when nesting ajax calls

Here's the issue. I'm extracting gmail contacts through an ajax call in javascript/jquery like this:
function getUserInfo() {
var xml_parse = "";
$.ajax({
url: SCOPE + '?max-results=9999&access_token=' + acToken
data: null,
success: function (resp) {
xml_parse = $.parseXML(resp);
callGmailHelperWebService(xml_parse);
},
dataType: "jsonp"
});
}
function callGmailHelperWebService(xml_parse) {
GmailHelperService.ConvertXMLToList(xml_parse, onSuccess, onFailed, null);
}
So, as you can see, if the initial ajax call is successful, i call a function which calls a web service that sits on the save server as my project (in fact, it's part of the project).
My web service (GmailHelperService) is wired up correctly, as I can definitely call it in other places (like right after this ajax call, for example). However, when I try to call it within the "success" portion of the ajax call, i get the following error:
Uncaught Error: SECURITY_ERR: DOM Exception 18
My theory is that this has something to do with cross-domain issues, but I can't understand why. And I certainly can't figure out how to fix this.
I'd appreciate any help.
JSONP is a data transfer method that involves sending your data in this format:
callback({"foo":"bar"});
As you can see, this is NOT xml. It is JSON wrapped in a callback method that will get executed when the request is done loading, thus allowing it to be cross-domain because it can be requested using a <script> tag.
You cannot simply change your dataType to JSONP and return xml, expecting it to work. XML != JSONP. You can however return XML in jsonp, for example, callback({"xml","... xml string here "}) but be mindful of quotes, all json keys and values must be wrapped in double quotes, inner-quotes need to be handled appropriately.
If your request is a same domain request (Same protocol, same subdomain, same domain, and same port,) then you can change your dataType to "XML" if you are returning XML. Otherwise, you need to either setup a proxy script to get the xml for you, or have your webservice return JSONP.
For example, the following urls are all considered cross-domain from each other.
http://example.com
http://www.example.com
https://example.com
https://www.example.com
http://example.com:8080
All of the above urls would be considered cross-domain, even if they are on the same server.

Categories

Resources