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
Related
I've got an http 501 error bubbling up in prod from this call:
return $.ajax({
url: finalUrl,
success: function (result) {
console.log('success call result');
console.log(result);
finalResult = result;
},
data: JSON.stringify(data),
type: 'PATCH',
contentType: 'application/json'
});
How can I return a mock simulating the error so I can test a fix outside of production? I looked at the response tab in chrome and I see an HTML message:
<HTML><HEAD>
<TITLE>Unsupported Request</TITLE>
</HEAD><BODY>
<H1>Unsupported Request</H1>
PATCH to http://demo.site.com/serviceName/v1/requests/9305e338-666a-e611-8516-000c291891bb not supported.<P>
Reference #8.f0fd717.1472154919.9959c96
</BODY></HTML>
We suspect that the API is not being hit at all, blocked by a firewall. I don't know if I should expect a string or object in this case? If object, then what are the members of that object?
Fiddler says:
Server: AkamaiGHost
Mime-Version: 1.0
Content-Type: text/html
Content-Length: 350
Expires: Thu, 25 Aug 2016 20:21:49 GMT
Date: Thu, 25 Aug 2016 20:21:49 GMT
Connection: close
We suspect that the API is not being hit at all, blocked by a firewall.
From the error, it looks like you're hitting a back-end that isn't configured for that request-type.
See these questions for a potential solution, assuming you control the back-end too.
Does tomcat support http PATCH method?
How do I stop Apache httpd from rejecting HTTP PATCH requests?
If you do control the back-end, but the above doesn't help, make sure that your controller function supports that request method. In Spring, for example, you have to declare that explicitly:
#Controller
MyController {
#Requestmapping(value = "/api/patchTheThing", method=RequestMethod.PATCH)
#ResponseBody String patchTheThing(....) {
...
}
}
Just set up an endpoint on a server of your choice and use your web server configure or coding language of your choice to issue a 501 response. But the problem seems pretty clear, the server is not expecting a PATCH request. If you had some networking problem you would not be getting a response at all.
you should strongly consider making sure your JavaScript code handles both happy path / success outcome as well as other types off sever response outcomes so your application can better handle how it wants to recover from such errors.
I've been struggling with this problem for the last few hours, and every tutorial points toward the solution that I have implemented but it doesn't work.
Basically my PUT request returns an error:
PUT http://localhost:8083/stockapi/rest/stocks/5485cba248673a0dd82bb86f 400 (Bad Request)
When I intercept the request, I see that it contains a $promise and $resolved data element:
> {"id":"5485cba248673a0dd82bb86f","name":"iShares ESTOCK DivXXX","ticker":"AMS:IDVY","url":"https://www.google.com/finance?q=AMS%3AIDVY&ei=F5BxVLiCB8GlwQPJ1YD4DQ","currency":"EUR","currentPrice":19.81,"currentPriceInEuro":19.81,"lastModified":1418054562234,"historyStockPrices":[{"timestamp":1418054562234,"price":19.81}],"$promise":{},"$resolved":true}
This makes sense since I'm using the ngResource object -- but every tutorial shows that the following code should be able to handle it, but it doesn't.
Note/edit: if i PUT the JSON object without the "$promise" and "$resolved" elements through an external program (such as Postman REST client) then it works fine.
Factory:
.factory('Stock',function($resource){
return $resource('http://localhost:8083/stockapi/rest/stocks/:id',
{ id: '#id' },{
update: { method: 'PUT' },
show: { method: 'GET' }
}); });
Controller (note: doing 4 updates but none of them work, 4 times the same Bad Request):
.controller('StockEditController',function($scope,$log,$http,$state,$stateParams,Stock){
$scope.stock = Stock.get({id:$stateParams.id});
$scope.updateStock=function(stock) {
Stock.update(stock);
stock.$update();
Stock.update($scope.stock);
$scope.stock.$update();
$state.go('stocks');
};
});
I'm really clueless right now how to use the ngResource object in the correct way so that I can use it to put/post to my webservice. Any ideas?
Thanks!
EDIT:
Chrome network output:
Response header
Remote Address:[::1]:8080
Request URL:http://localhost:8080/stockapi/rest/stocks/5485cba248673a0dd82bb86f
Request Method:PUT
Status Code:400 Bad Request
Request Headersview parsed
PUT /stockapi/rest/stocks/5485cba248673a0dd82bb86f HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 355
Pragma: no-cache
Cache-Control: no-cache
Accept: application/json, text/plain, */*
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36
Content-Type: application/json;charset=UTF-8
Referer: http://localhost:8080/stockapi/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Request Payloadview parsed
{"id":"5485cba248673a0dd82bb86f","name":"iShares ESTOCK DivXXXYYY","ticker":"AMS:IDVY","url":"https://www.google.com/finance?q=AMS%3AIDVY&ei=F5BxVLiCB8GlwQPJ1YD4DQ","currency":"EUR","currentPrice":19.81,"currentPriceInEuro":19.81,"lastModified":1418054562234,"historyStockPrices":[{"timestamp":1418054562234,"price":19.81}],"$promise":{},"$resolved":true}
Response Headersview parsed
HTTP/1.1 400 Bad Request
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Language: en
Content-Length: 968
Date: Tue, 09 Dec 2014 06:36:24 GMT
Connection: close
According to the docs you are not quite using the update action correctly.
So really your updateStock method should be:
$scope.updateStock=function(stock) {
Stock.update({id: stock.id}, stock);
Stock.update({id: $scope.stock.id}, $scope.stock); //not sure why you have 2 calls here
$state.go('stocks');
};
Just looking at the factory definition and how it differs from mine, you should change that second parameter of factory definition into array to something like this:
.factory('Stock',[$resource, function($resource){
return $resource('http://localhost:8083/stockapi/rest/stocks/:id',
{ id: '#id' },{
update: { method: 'PUT' },
show: { method: 'GET' }
});
}]);
Not sure if this is the issue but that is at least significantly different to angular docs' definition on dependency injection here: https://docs.angularjs.org/guide/di
If not, could you also print out the contents of $scope.stock after the GET returns the data there?
I know this question is super old, but I stumbled upon the same issue and found this SO question as well as this question:
http://www.scriptscoop2.com/t/fddc3f0a1f6f/angularjs-using-ngresource-for-crud-adds-extra-key-value-when-using-save.html
There was 1 answer which explained that the issue is coming due to CORS (cross origins). Which means that your server side needs to allow it. If you are using Spring MVC it would be enough to add the org.springframework.web.bind.annotation.CrossOrigin annotation at the controllers request mapping:
#CrossOrigin
#RequestMapping(value = "/product/{id}", method = RequestMethod.POST)
#ResponseBody
public void editProduct(#PathVariable("id") final long id, #RequestBody final ProductDto productDto) {
// your code
}
I'm building a web app with Django. I have a bunch of API calls in Javascript via Ajax (jQuery v1.8.3).
Most of them work, but a particular one results in a return object with status 0 and this message as the statusText:
[Exception... "'JavaScript component does not have a method named: "available"' when calling method: [nsIInputStream::available]" nsresult: "0x80570030 (NS_ERROR_XPC_JSOBJECT_HAS_NO_FUNCTION_NAMED)" location: "JS frame :: http://127.0.0.1:8000/media/js/jquery.js :: .send :: line 8434" data: no]
The corresponding line in jQuery is xhr.send( ( s.hasContent && s.data ) || null );
However, this occurs only in Firefox. Chrome works fine. Again, other requests do work. The only thing which sets this one apart is the DELETE http method.
The request is as follow (HTTP network data shown in Chrome – Firebug doesn't show anything in Firefox):
Request URL: http://127.0.0.1:8000/api/reservation/13/
Request Method: DELETE
Status Code: 400 BAD REQUEST (This is expected)
Request Headers
Accept: application/json, text/javascript, */*; q=0.01
Content-Length: 15
Content-Type: application/json
Origin: http://127.0.0.1:8000
Referer: http://127.0.0.1:8000/reservation/
X-Requested-With: XMLHttpRequest
Request Payload
[object Object]
Response Headers
Cache-Control: no-cache
Content-Type: text/html; charset=utf-8
Date: Tue, 02 Apr 2013 19:18:35 GMT
Server: WSGIServer/0.1 Python/2.7.2
On the server, I don't receive any request.
The JS code is (taken directly from Firebug Watch at breakpoint):
options = {
contentType: "application/json",
data: Object {},
dataType: "json",
processData: false,
type: "DELETE",
url: "/api/reservation/13/",
error: function(),
success: function()
};
$.ajax(options);
I also did try to disable all extensions in FF. I run v20.0.
The problem was a combination of Firefox with jQuery/XMLHttpRequest and sending an object via HTTP DELETE. Once JSON'ifying the object via JSON.stringify() everything worked.
Still, a strange exception for Firefox to throw.
Thanks to freddyb for that idea.
The problem was with the property called processData within the $.ajax function. When this property is supplied as "false" (don't know why) Firefox doesn't like it, and as consequence, the browser doesn't digest the JSON request/response package. Chrome and Safari works just fine.
This happens (as of 2014 with FireFox 32) with any non-GET AJAX request when the request data object is an empty object, like {}. I am using Mithril.js and it may be related to the fact that Mithril always sets a Content-Type for non-GET requests. This was absolutely repeatable once I knew the trigger.
(Note that the "non-GET" part may not be entirely accurate -- Mithril ignores the data object if it's a GET so sending an empty object with GET using the underlying AJAX object may also fail in the same way.)
Counter-intuitively, setting data to an empty string, "", does not fail in this way, so that was my work-around. I actually don't set data at all when there is none, and if it's unset by the time I send the request (in my AJAX wrapper) I default it to "".
It sounds like you have a buggy Firefox extension installed which is trying to examine the XMLHttpRequest data and failing....
I suggest you try http://support.mozilla.org/en-US/kb/troubleshoot-firefox-issues-using-safe-mode or just disabling whatever Firefox extensions are involved.
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');
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?