jQuery $.ajax stripping out JSON object properties in Safari - javascript

I am using the following code:
$.ajax( {
url: "http://www.earthquakescanada.nrcan.gc.ca/api/earthquakes/latest/7d.json",
dataType: 'json',
success: successHandler
} );
var successHandler = function ( data ) {
console.log( data );
}
For some reason and only in Safari, the "location" property for the objects returned are stripped out. Can anyone explain why and suggest a solution?

It's not a jQuery or $.ajax problem, but the json resource you are trying to get, has a kind of user agent controller.
Try to open the url in Chrome and then in Safari, you will see two different json files from the same url http://www.earthquakescanada.nrcan.gc.ca/api/earthquakes/latest/7d.json

You could also try using $.getJSON(...) instead of $.ajax(...), since that will get you the parsed json object in your data variable

Related

Jquery Ajax jsonp invalid token error for invalid json but it appears correct

Im currently trying to use the OSRS api in jquery.
I have used it prior to this with httparty in rails but wanted to see if i could do it in a javascript way.
However i seem to be having a problem parsing the contence of the response despite it appearing valid.
My code can be seen below:
// jquery Stuff
$( document ).ready(function() {
var url_test = "http://services.runescape.com/m=itemdb_oldschool/api/catalogue/detail.json?item=207&format=json";
$.ajax({
crossDomain: true,
dataType: "jsonp",
url: url_test ,
}).done(function ( data ) {
console.log(data);
alert( "Load was performed." );
});
});
This is the 'broken' responce i get from the api which throws the error of Uncaught SyntaxError: Unexpected token :
{"item":{"icon":"http://services.runescape.com/m=itemdb_oldschool/1492081307848_obj_sprite.gif?id=207","icon_large":"http://services.runescape.com/m=itemdb_oldschool/1492081307848_obj_big.gif?id=207","id":207,"type":"Default","typeIcon":"http://www.runescape.com/img/categories/Default","name":"Grimy ranarr weed","description":"It needs cleaning.","current":{"trend":"neutral","price":"7,338"},"today":{"trend":"negative","price":"- 20"},"members":"true","day30":{"trend":"positive","change":"+2.0%"},"day90":{"trend":"positive","change":"+8.0%"},"day180":{"trend":"positive","change":"+8.0%"}}}
Is there someway that i can load this data correctly. I think its because of using jsonp if i where to guess. However i cant seem to load the api threw json data type as it throws a CORS error. So im a little stuck and any help with this would be great thanks !
What you're returning is JSON, not JSONP. Your response looks like
{"name" : "Joe"} //json format
and jQuery is expecting something like this:
jQuery42534534636363({"name" : "Joe"}) //jsonp format
If you actually need to use JSONP to get around the same origin policy, then the server serving 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.
// jquery Stuff
$( document ).ready(function() {
var url_test = "http://services.runescape.com/m=itemdb_oldschool/api/catalogue/detail.json?item=207&format=json";
$.ajax({
crossDomain: true,
dataType: "json",
url: url_test ,
}).done(function ( data ) {
console.log(data);
alert( "Load was performed." );
});
});
JSONP Example (a wrapping function)
JSON Example

Difference between ajax and getJSON calls?

I have a page being served from a Web.API app located at http://server/application. On the client side, I am doing a GET to pull some data from the servers. The problem is what I thought should work does not.
This code works:
$.ajax( {
url: "api/slideid/getdirectories/",
dataType: 'json',
success: function ( data ) {
setPaths( data );
}
} );
But this does not:
$.getJSON( "api/slideid/getdirectories/",
function ( data ) {
setPaths( data );
} );
In the first example I see in fiddler that the url it is trying to retrieve the data from is http://server/application/api/slideid/getdirectories, which is correct.
In the second, it is http://server/api/slideid/getdirectories, which is not right. I was thinking that these two methods of json GET were the same.... but it seems they are not?
Interestingly, BOTH these methods work on my local dev box- it is only on my staging server that one works and the other does not. IIS settings are identical as far as I can tell- and I dug in pretty good to check.
So I'm wondering why getJSON does not work, when the jQuery docs state that getJSON is just shorthand for the .ajax call?
EDIT: I had put in an explicit version of getJSON hoping to show that they were very similar calls, but the 'real' getJSON call is now there.
You have a wrong implementation of $.getJSON() This should be:
$.getJSON(url, {data:data}, function(data){
alert(data);
});
where {data:data} is optional.
From the docs:
This is a shorthand Ajax function, which is equivalent to:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
$.getJSON(url, {data:data}, ....
wrong syntax

Javascript automatically parsing nested object

This is more a question of procedure than anything else. I'm curious why this happens and I can't seem to find any documentation on this "feature" within the ECMA script documentation.
When I make an AJAX call within jQuery to my server, it returns the following JSON response to the page:
{"version":"v1","status":"OK","timestamp":"2013-02-14 10:32:45","data":"true","error":""}
With this string I have to call jQuery.parseJSON(string); to get it as an object, and the be able to reference it as an object.
However, when my server returns something like this:
{"version":"v1","status":"OK","timestamp":"2013-02-14 10:12:19","data":{"a":"asgsadfga","b":false,"c":[]},"error":""}
Javascript automatically loads this an an object without the need to parse. It would seem that because this example returns a nested object, despite the fact it was returned from the server as a string, Javascript will immediately recognize that, and parse the string for me.
Is this expected functionality, and if so, can anyone point me to the documentation of this?
EDITED:
Here is the offending AJAX call:
jQuery.ajax({
url: url,
type: 'GET',
async: false,
success: function (result) {
console.log(result)
}
Make sure that your server sets the proper Content-Type response HTTP header:
Content-Type: application/json
So that jQuery will automatically parse the JSON string returned by your server to a javascript object which will be passed as argument to your success callback.
Or if for some reason you've got some broken server side script which you have no control over you could set the dataType parameter to force jQuery to parse the result as JSON:
$.ajax({
url: '/script.cgi',
type: 'POST'
dataType: 'json',
success: function(result) {
// result will be a javascript object
}
});
But obviously the proper thing to do is to fix your server side script to return the proper Content-Type response header.
According to ajax() in jQuery API Documentation under dataType:
dataType (default: Intelligent Guess (xml, json, script, or
html))Type: String The type of data that you're expecting back from
the server. If none is specified, jQuery will try to infer it based
on the MIME type of the response (an XML MIME type will yield XML, in
1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).
Hope this helps.
You should specify dataType to be json in your $.ajax call. dataType is the MIME you are expecting to receive from the server. contentType is what the server is expecting from you.

Is there a name for a pre-loaded AJAX object?

Is there a name for a pre-loaded AJAX object stored in memory?
If I wanted to use this code:
function GetXML() {
$.ajax({
type: "GET",
url: "questions.xml",
dataType: "xml",
success: function(xml) {
} //close success
});//close AJAX
}; //close function GetXML
to load some XML, how would I store this data on an object? Would I have to create a new variable on the object to store this XML? That's what I've found. If so, what would the type would the variable be? (e.g. String, Int, something of that nature)
Would it be 'Object XML' or something of that sort?
Thanks, Elliot Bonneville
Since you are setting dataType: 'xml' in the AJAX request, jQuery will parse the response into an XMLDocument object.
Note that there are certain circumstances where you will need to do this manually. (Related to an IE bug, of course)
You'll have to use a JavaScript XML parser to convert it to an object. There are a lot of pre-made ones, but if you want it for something simple check: http://www.w3schools.com/Xml/xml_parser.asp
Since you're using jQuery already, parse the data like you parse the elements of an html document with regular $() calls on elements in the xml.
you could use jQuery('example

How do I get the entire XML string from a XMLDocument returned by jQuery (cross browser)?

I have tried and failed to find out how to get the entire XML string from the XMLDocument returned by a GET. There are a lot of questions on SO on how to find or replace specific elements in the object, but I can't seem to find any answer to how to get the entire document as a string.
The example I'm working with is from here. The "do something with xml"-part is where I'm at at the moment. I get the feeling that this should be really trivial, but I fail to find out how. Is there an "xml.data()" or similar that can be used for this purpose?
$.ajax({
url: 'document.xml',
type: 'GET',
dataType: 'xml',
timeout: 1000,
error: function(){
alert('Error loading XML document');
},
success: function(xml){
// do something with xml
}
});
The use case is that I want to feed the xml to flash plugin and for that I need the actual XML as a string.
If you want both, get the response as XML Document and as string. You should be able to do
success: function(data){
//data.xml check for IE
var xmlstr = data.xml ? data.xml : (new XMLSerializer()).serializeToString(data);
alert(xmlstr);
}
If you want it as string why do you specify dataType:xml wouldn't then dataType:text be more appropriate?
I need the actual XML as a string
You want it as plain text instead of XML object? Change dataType from 'xml' to 'text'. See the $.ajax documentation for more options.
You can also easily convert an xml object to a string, in your java script:
var xmlString = (new XMLSerializer()).serializeToString(xml);
If you only need a string representing the xml returned from jquery, just set your datatype to "text" rather than trying to parse the xml back into text. The following should just give you raw text back from your ajax call:
$.ajax({
url: 'document.xml',
type: 'GET',
dataType: 'text',
timeout: 1000,
error: function(){
alert('Error loading XML document');
},
success: function(xml){
// do something with xml
}
});
Although this question has already been answered, I wanted to point out a caveat: When retrieving XML using jQuery with Internet Explorer, you MUST specify content-type to be "text/xml" (or "application/xml") or else you will not be able to parse the data as if it were XML using jQuery.
You may be thinking that this is an obvious thing but it caught me when using Mozilla/Chrome/Opera instead of IE. When retrieving a "string" of XML with a content-type of "text", all browsers except IE will still allow you to parse that data (using jQuery selectors) as if it were XML. IE will not throw an error and will simply not return any results to a jQuery selection statement.
So, in your example, as long as you only need the string-serialized version of the XML and will not expect jQuery to do any sort of selection on the XML DOM, you can set the content-type to "text". But if you ALSO need to parse the XML with jQuery, you will need to write a custom routine that serializes the XML into a string for you, or else retrieve a version of the XML with content-type "xml".
Hope that helps someone :)
You can get the native XMLHttpRequest object used in the request.
At the time i'm posting this answer, jQuery docs state a few ways to do so.
One of them is via the third argument of the success callback:
success: function(xml, status, xhr){
console.log(arguments);
console.log(xhr.responseXML, xhr.responseText);
console.log('Finished!');
}
For a complete example:
https://jsfiddle.net/44m09r2z/

Categories