I am using the Framey API for video recording. When I make a request I get back the json response I expect, but an error is raised:
Uncaught SyntaxError: Unexpected token :
Here's the javascript
var url = "http://framey.com/api/videos/ba9bd910-549d-012e-32f4-549a20bdfc52?
api_key=7VNKGLJZLKSASZ0FXN2TVSZQU&signature=41B08D68E0A4AC2DD91107BBD6AD08B8&time_stamp=1304447242";
$("button").click(function() {
$.ajax({
url: url,
dataType: 'json',
crossDomain: true
}).done(function() {
$(".video").html("here it is babyF!");
});
});
The url is just an example url from Framey's website, I don't know if it works. From reading this question Uncaught SyntaxError: Unexpected token :, I think that I maybe having the same problem. The selected answer to that question is
Just an FYI for people who might have the same problem -- I just had
to make my server send back the JSON as application/json and the
default jQuery handler worked fine.
I don't think I can effect the way Framey is sending me back the data, so I'm not sure how to fix this. Maybe it is something else all together? Thanks in advance and let me know if you need more information.
=========EDIT============
Here is the response from Framey that is giving me the error:
{"success":true,"video":{"name":"6d235a90-7b4b-012f-f97e-12313d297e67","filesize":1335504,"duration":20.48,"state":"uploaded","views":1,"data":{},"flv_url":"http://framey.com/videos/source/6d235a90-7b4b-012f-f97e-12313d297e67.flv","mp4_url":"http://framey.com/videos/source/6d235a90-7b4b-012f-f97e-12313d297e67.mp4","large_thumbnail_url":"http://framey.com/thumbnails/large/6d235a90-7b4b-012f-f97e-12313d297e67.jpg","medium_thumbnail_url":"http://framey.com/thumbnails/medium/6d235a90-7b4b-012f-f97e-12313d297e67.jpg","small_thumbnail_url":"http://framey.com/thumbnails/small/6d235a90-7b4b-012f-f97e-12313d297e67.jpg"}}
I think it is something about Framey putting "application/javascript" in the place where it should be saying "application/json"
============ EDIT 2 =================
Here are the headers for the response, I got these by looking at the "Network" section of the console in Chrome.
Request URL:http://www.framey.com/api/videos/32a7aaf0-7c3a-012f-37bd-12313b093125?api_key=00000000&signature=624643a3481b2a2c2bdb6c7cc29c506e&time_stamp=1536494436&callback=jQuery17202607689620926976_1336594235235&_=1336594483714
Request Method:GET
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Cookie:__utma=229279307.404664337.1336485291.1336573199.1336589854.6; __utmc=229279307; __utmz=229279307.1336485291.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); _video-recorder_session=BAh7B0kiD3Nlc3Npb25faWQGOgZFRiIlN2VjODBiYWM1NDk2MDlkYTg2ZTY0NzEzNDA5Zjg3ZGJJIhBfY3NyZl90b2tlbgY7AEZJIjE4aW5KVktxakhyVTRvVGY0RXZlNkVkMU9lV0p1NUEzR01rVzlNK1hRWEJ3PQY7AEY%3D--b9a5f6cf08d7539d2bf9ebebc83ce96b0d070615
Host:www.framey.com
Referer:http://localhost:3000/questions/1
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.168 Safari/535.19
Query String Parametersview URL encoded
api_key:000000000000
signature:624643a3481b2a2c2bdb6c7cc29c506e
time_stamp:1536494436
callback:jQuery17202607689620926976_1336594235235
_:1336594483714
Response Headersview source
Cache-Control:max-age=0, private, must-revalidate
Connection:keep-alive
Content-Length:709
Content-Type:text/javascript; charset=utf-8
ETag:"5e8393861da01fa2effd911365a90e6b"
Server:nginx/1.0.10 + Phusion Passenger 3.0.11 (mod_rails/mod_rack)
Set-Cookie:_video-recorder_session=BAh7B0kiD3Nlc3Npb25faWQGOgZFRiIlN2VjODBiYWM1NDk2MDlkYTg2ZTY0NzEzNDA5Zjg3ZGJJIhBfY3NyZl90b2tlbgY7AEZJIjE4aW5KVktxakhyVTRvVGY0RXZlNkVkMU9lV0p1NUEzR01rVzlNK1hRWEJ3PQY7AEY%3D--b9a5f6cf08d7539d2bf9ebebc83ce96b0d070615; path=/; HttpOnly
Status:200
X-Powered-By:Phusion Passenger (mod_rails/mod_rack) 3.0.11
X-Runtime:0.060476
X-UA-Compatible:IE=Edge,chrome=1
Of particular interest is the content-type header: it is text/javascript.
Where did you find that demo code (I could not find it on the Framey site)? I suspect you will run into cross-domain issues trying to use the Framey REST API from the client. Is your code on a publicly accessible server somewhere that we can take a look?
Related
Trying to make a call and retrieve a very simple, one line, JSON file.
$(document).ready(function() {
jQuery.ajax({
type: 'GET',
url: 'http://wncrunners.com/admin/colors.json' ,
dataType: 'jsonp',
success: function(data) {
alert('success');
}
});
});//end document.ready
Here's the RAW Request:
GET http://wncrunners.com/admin/colors.json?callback=jQuery16406345664265099913_1319854793396&_=1319854793399 HTTP/1.1
Host: wncrunners.com
Connection: keep-alive
Cache-Control: max-age=0
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.106 Safari/535.2
Accept: */*
Referer: http://localhost:8888/jquery/Test.html
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Here's the RAW Response:
HTTP/1.1 200 OK
Date: Sat, 29 Oct 2011 02:21:24 GMT
Server: Apache/1.3.33 (Unix) mod_ssl/2.8.22 OpenSSL/0.9.7d SE/0.5.3
Last-Modified: Fri, 28 Oct 2011 17:48:47 GMT
ETag: "166a2402-10-4eaaeaff"
Accept-Ranges: bytes
Content-Length: 16
Content-Type: text/plain
Connection: close
{"red" : "#f00"}
The JSON is coming back in the response (red : #f00), but Chrome reports Uncaught SyntaxError: Unexpected token : colors.json:1
If I navigate directly to url itself, the JSON is returned and is displayed in the browser.
If I paste the contents of colors.json into JSLINT, the json validates.
Any ideas why I can't get this error and I never make it to the success callback?
EDIT - the jQuery.ajax() call above runs perfect at jsfiddle.net, and returns the alert 'success' as expected.
EDIT 2 - this URL works fine 'http://api.wunderground.com/api/8ac447ee36aa2505/geolookup/conditions/q/IA/Cedar_Rapids.json' I noticed that it returned as TYPE: text/javascript and Chrome did not throw the Unexpected Token. I've tested several other url's and the ONLY one that does not throw the Unexptected Token is the wunderground that is returned as TYPE: text/javascript.
Streams returned as text/plain and application/json are not being parsed correctly.
You've told jQuery to expect a JSONP response, which is why jQuery has added the callback=jQuery16406345664265099913_1319854793396&_=1319854793399 part to the URL (you can see this in your dump of the request).
What you're returning is JSON, not JSONP. Your response looks like
{"red" : "#f00"}
and jQuery is expecting something like this:
jQuery16406345664265099913_1319854793396({"red" : "#f00"})
If you actually need to use JSONP to get around the same origin policy, then the server serving colors.json needs to be able to actually return a JSONP response.
If the same origin policy isn't an issue for your application, then you just need to fix the dataType in your jQuery.ajax call to be json instead of jsonp.
I have spent the last few days trying to figure this out myself. Using the old json dataType gives you cross origin problems, while setting the dataType to jsonp makes the data "unreadable" as explained above. So there are apparently two ways out, the first hasn't worked for me but seems like a potential solution and that I might be doing something wrong. This is explained here [ https://learn.jquery.com/ajax/working-with-jsonp/ ].
The one that worked for me is as follows:
1- download the ajax cross origin plug in [ http://www.ajax-cross-origin.com/ ].
2- add a script link to it just below the normal jQuery link.
3- add the line "crossOrigin: true," to your ajax function.
Good to go! here is my working code for this:
$.ajax({
crossOrigin: true,
url : "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.86,151.195&radius=5000&type=ATM&keyword=ATM&key=MyKey",
type : "GET",
success:function(data){
console.log(data);
}
})
I had the same problem and the solution was to encapsulate the json inside this function
jsonp(
.... your json ...
)
That hex might need to be wrapped in quotes and made into a string. Javascript might not like the # character
I'm trying to get some JSON data from a REST API, but when I call it cia an AJAX request with dataType param as jsonp it gives me an error that the jQuery 'callback was not called'. This is the error message:
Error: Status: parsererror Message: Error: jQuery2130732580496231094_1429605569499 was not called
So, if I try to make this request without jsonp, using JSON as the dataType, it gives me another error about the CORS:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
I know this is an idiot question, but I've read about CORS and just don't get where to put it's params to enable it. For me, the right is to use the first method that I've used, but after looking for an answer for that problem, I just don't understand anything. If someday I could understand where to put the CORS I should be use to make the request as another way.
So they are my questions, here is my code:
$.ajax({
url: 'eztvapi.re/shows/1';,
type: 'GET',
dataType: 'jsonp',
crossDomain: true,
success: function(data) {
//data = JSON.parse(data);
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error: Status: " + textStatus + " Message: " + errorThrown);
}
});
This are my headers request from the console:
Remote Address:216.58.222.12:443
Request URL:http://eztvapi.re/shows/1?callback=jQuery213010618196451105177_1429606458524&_=1429606458525
Request Method:GET
Status Code:200 OK
Response Headers
cache-control:private
content-encoding:gzip
content-type:application/json; charset=utf-8
date:Tue, 21 Apr 2015 08:54:22 GMT
etag:W/"0hnqCn40L98JLmwY2UfUlg=="
server:nginx
status:200
vary:Accept-Encoding
via:1.1 Chrome-Compression-Proxy
x-powered-by:Express
x-response-time:32ms
x-served-by:us-la3
Request Headers
:authority:eztvapi.re
:method:GET
:path:/shows/1?callback=jQuery213010618196451105177_1429606458524&_=1429606458525
:scheme:http
accept:*/*
accept-encoding:gzip, deflate, sdch
accept-language:pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4
chrome-proxy:ps=1429584828-1395746459-275388119-220935266, sid=a259cd2eeb457c7a40ff6367868ef723, c=win, b=2311, p=90
user-agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36
Query String Parameters
view source
view URL encoded
callback:jQuery213010618196451105177_1429606458524
_:1429606458525
And this are the json object that the request returns, BUT IT ONLY APPEARS ON THE CONSOLE NETWORK PART:
0: {_id: "tt0944947",…}
1: {_id: "tt0903747",…}
2: {_id: "tt0898266",…}
3: {_id: "tt1520211",…}
4: {_id: "tt0773262",…}
5: {_id: "tt0460649",…}
6: {_id: "tt1475582",…}
7: {_id: "tt2193021",…}
8: {_id: "tt1796960",…}
9: {_id: "tt1119644",…}
10: {_id: "tt0411008",…}
I've done recently a lot of requests for another rests,so i think the client's side is correctly. This is a new server that i'm testing my requests, but this is not my server domain, this belows to a popular rest server and i believe that supports json call. What is funny and i've asking myself since i've start with this new one is the response that i'm getting. You can see that server answers my request with the correctly data, but i can't get the data to my javascript, to print it or process it.
Thank you for any help.
Error: Status: parsererror Message: Error: jQuery2130732580496231094_1429605569499 was not called
The server you are requesting data from has to support JSONP in order for you to make a successful JSONP request to it.
See the Wikipedia article on the subject for details of how to do that.
I've read about CORS and just don't get where to put it's params to enable it.
In the HTTP response headers of the service you are making the request to.
e.g. Your page on example.com wants to use JS to get data from example.net. Therefore example.net has to tell the user's browser that example.com is allowed access to the data.
To enable CORS requests, you have to allow this type of request from your server part and create a request from your client which will be allow to get cors resources :
Only use GET, HEAD or POST and content type application/x-www-form-urlencoded, multipart/form-data, or text/plain.
Your client part seems to be correct, I think you have to deal with the server to allow this type of request.
you can have more informations here
Finally, after a couple of days studying this problem i've solved this. Not from the most easy way, but... solved :D
I wrote an app with express and request on NodeJs, and using the request it returned me all the json object. Now i could just send it to my javascript var with the express.
Thanks for all the replies guys! Peace.
After searching for a while, I cannot find the answer yet.
My problem is when I call a web service function setRequestHeader, I got the error "not allowed by Access-Control-Allow-Origin".
Here is my javaScript code:
var loginController = new sap.ltst.login.loginController({controllerName: "sap.ltst.login.loginController"});
var session = loginController.login("I051486", "123456789");
var config = {};
$.ajax({
beforeSend: function(req) {
req.setRequestHeader('Authentication', 'Authentication-Token ' + session.session_token);
},
url : "http://localhost:8081/com.sap.st.gtpapi/program/"
+ this.program + "/configs",
dataType : 'json',
type : 'GET',
async : false,
success : function(data) {
config = data;
}
});
return config;
In web service side, I have a function that I can enable or disable the authentication. I tried to set the auth as false (not check the auth) then remove setRequestHeader, I got no error and the web service returns me some data.
In another way I tried to put it back, I got the error.
XMLHttpRequest cannot load http://localhost:8081/gtpapi/program/Business%20Intelligence%20platform%204.1%20(BI%20Aurora%204.1)/configs. Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin.
So I don't think that it's the problem of the auth because in the web service side, I disable the auth verification.
Let's move to the web service side, this is the interface:
public static final String HEADER_AUTH_TOKEN = "Authentication-Token";
#GET
#Consumes({MediaType.APPLICATION_JSON})
#Produces({MediaType.APPLICATION_JSON})
#Path("/guid_{planId}/packages/{packId}/{results}")
public Response setPackageResult(#PathParam("planId") final String planGuid, #PathParam("packId") final String packGuid, #PathParam("results") final String results, #HeaderParam(WebServiceBase.HEADER_AUTH_TOKEN) String token);
This is the header response et request on Chrome:
Request URL:http://localhost:8081/com.sap.st.gtpapi/program/SBOP%20EXPLORER%204.1/configs
Request Method:OPTIONS
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Charset:UTF-8,*;q=0.5
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,fr;q=0.6
Access-Control-Request-Headers:accept, authentication, origin
Access-Control-Request-Method:GET
Cache-Control:no-cache
Connection:keep-alive
Host:localhost:8081
Origin:http://localhost:8080
Pragma:no-cache
Referer:http://localhost:8080/LTST_Frontend/index.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31
Response Headersview source
Allow:GET,OPTIONS,HEAD
Content-Length:0
Content-Type:text/xml
Date:Fri, 02 Aug 2013 15:44:10 GMT
Server:Apache-Coyote/1.1
I'm not sure I did some mistake whether the problem comes from javaScript or web service. Any ideas?
Put any header you want to send in the safe list:
header("Access-Control-Allow-Headers: Authentication, X-Custom-Header, .. etc");
This should be part of the CORS headers on the receiving domain.
Edit: In my case, The the reason that it was not returning to correct information is that I was trying to use JSONP to connect to a CORS data setup, whereas the server did not have it set up for my particular computers access. I needed to talk to someone and adjust the permissions of the config file for the server. Thats what was really going on, and i couldnt figure it out because i thought CORS and JSONP were synonymous, but in fact there are different ways they are carried out and certain server permissions which need to be set.
Brief: I have an $.ajax request which pings a server looking data. It fails, but data shows success.
Going into the Network, it SHOWS the response. I want it. Its right out of my grasp.
Errors: Says it fails, but the return is:
{"readyState":4,"status":200,"statusText":"success"}
So, it means that somewhere on the client side, it was flagged. The response is:
["Asset","AssetElementDefMap","AssetFile","AssetFileCategory","AssetFileCategoryObjectMap","AssetFilesFieldMap","AssetFilesReportMap","AssetTree","AssetType","BicUrl","CancelledUpload","CurrentValue","DataTypeInstanceMembers","DataTypeInstances","DataTypeMembers","DeviceDatabase","ElementDef","ElementDefEnvironment","ElementDefFormMap","ElementDefManual","ElementDefStructUnit","ElementDefStructUnitList","Field","FieldChoice","FieldFormScriptMap","FileType","FileTypeAssetFileCategoryMap","ForgotPassword","Form","FormScriptFunction","FormType","in_id","InspectionType","Inspector","MobileFormOSMap","MobileReportTypeFormMap","MobileReportTypeFormTypeMap","ProfileProperty","Report","ReportSubAssetMap","ReportType","ReportTypeAssetTypeMap","ReportTypeInspectionTypeMap","ReportValue","WorkingSet"]
The Headers are:
**Request**
URL:http://xx.xxx.xx.x/mas3/DataSources/inspecttech.inspecttech/Schema/Classes/?callback=jQuery172021616409649141133_1374243099954&_=1374243124683
Request Method:GET
Status Code:200 OK
**Request Headers**
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Authorization:Basic bmRvdG1vYnguaGluc3BlY3R0ZWNoOjU0NjdjZTg2ZTdiMzc4MTNjYmQ0ZGQ3MTM1MDJkOGVjNDNiYjUwMTU2NzJiNzAxNDczMDRjYzE5YjA5ZGIyN2EyODNiMzliNmY4YzIyN2UxNjY1MDk5NDcxYzBjOTFlODZhN2EzOTliZTgzMjliNGY1MzFjOWZhYWI3YjNkMjg1
Connection:keep-alive
Host:10.224.65.5
Referer:http://localhost:3033/BentleyFormIntegrationFrameset.aspx
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36
**Query String Parameters**
callback:jQuery172021616409649141133_1374243099954
_:1374243124683
**Response Headers**
Cache-Control:no-cache
Content-Language:en-US
Content-Length:801
Content-Type:application/json; charset=utf-8
Date:Fri, 19 Jul 2013 14:12:03 GMT
Expires:-1
Mas-License-Error-Id:NoClientLicense
Mas-License-Error-Message:Client's license is invalid.
Pragma:no-cache
Server:Microsoft-IIS/7.5
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
EDIT: AJAX REQUEST:
var u = "myusername";
var p = "mypass";
var up = u + ":" + p;
$.ajax({
type: "GET",
url: "http://xx.xxx.xx.x/mas3/DataSources/inspecttech.inspecttech/Schema/Classes/",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
headers: {Authorization: "Basic "+up},
success: function (r) {
alert("Success: " + JSON.stringify(r));
},
error: function (r) {
alert("Failure: " + JSON.stringify(r));
}
});
The response is:
Content-Type:application/json
["Asset","AssetElementDefMap",…,"WorkingSet"]
That's no JSONP script, but plain JSON (the "padding", ie. the callback function, is missing). Since the request is cross-domain, you're not allowed to access it - and executing it as a script fails even when the resource loads with a 200 OK status.
As the title suggests, I have the following:
$.ajax({
"url" : ...
, "type" : "GET"
, "dataType" : "JSON"
, "success" : function(response_data) {
that.data = response_data;
success(response_data);
}
, "onerror" : function(data) {
console.log(JSON.stringify(data));
}
});
But when I run it, I get
XML Parsing Error: syntax error Location: moz-nullprincipal
Looking at firebug, I see that the request was
Accept application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-us,en;q=0.5
Cache-Control max-age=0
Connection keep-alive
Host localhost:8888
Referer http://localhost:8888/
User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:13.0) Gecko/20100101 Firefox/13.0.1
X-Requested-With XMLHttpRequest
Any ideas?
Change "JSON" to lowercase "json" first. But this is the type that jQuery is expecting back from the server, it's not necessarily what the server will send.
Are you sure that the server is returning JSON? Worth a double-check. Have you looked at the response in Fiddler? If it's XML it's the server's issue, not the script's.
Ok great thanks to everyone tried to answer this.
But it turns out, as usual, I noob'ed out here.
The XML parsing error shown in firebug is not actually an error with the code, and firebug's failed attempt to guess it's XML and parse it.
My problem was elsewhere in the program and it was solved.
Upper vs lower case "JSON" did not make a difference.
Max
The real problem is that your server is not setting the 'Content-type' header. Set it to 'application/json'.
For example in node.js:
res.setHeader('Content-type', 'application/json');