YUI "Get" utility to parse JSON response? - javascript

The documentation page for the YUI "Get" utility says:
Get Utility is ideal for loading your
own scripts or CSS progressively
(lazy-loading) or for retrieving
cross-domain JSON data from sources in
which you have total trust.
...but doesn't have any actual examples for how to do so. Their one example doesn't actually request a JSON document from a remote server, but instead a document containing actual JavaScript along with the JSON data.
I'm just interested in the JSON response from the Google Maps API HTTP (REST) interface. Because I can't do cross-site scripting with the "Connect" utility, I am trying the "Get" utility. But merely inserting some JSON data into the page isn't going to do anything, of course. I have to assign it to a variable. But how?
Also, just inserting JSON data into the page makes Firefox complain that there's a JavaScript error. And understandably! Plain ol' JSON data isn't going to parse as valid JavaScript.
Any ideas?

Normally in this case the easiest thing to do is to return javascript that calls a callback with the json. For example:
function xdCallback( json ) {
// here I can do whatever I need with json, maybe
SomeModule.heresTheJson( json );
// or
globalVar.json = json;
// etc
}
And so on your server side you return not just JSON but instead something like:
xdCallback( { json: 'goes', here: true } );
...execute the 'script' when you get it via your ajax call and you're set.

OK. Looks like without Google's HTTP Geocoding interface supporting JSONP, there is no way to do this. :(

Sean -- You may find that YUI Connection Manager's XDR support is what you're looking for --
http://developer.yahoo.com/yui/examples/connection/xdr.html (YUI 2)
http://developer.yahoo.com/yui/3/examples/io/io-xdr.html (YUI 3)
Use Connection Manager (YUI 2) or IO (YUI 3) to bring in the JSON, and then use the JSON component in either codeline to parse the JSON once it's loaded.
If Google or Yahoo! has the necessary cross-domain support on the relevant servers, you should be in business.
-Eric

I have used YAHOO.lang.JSON.parse to parse a string to json. Also the stringify method can be used to go from JSON back to a string:
http://developer.yahoo.com/yui/docs/YAHOO.lang.JSON.html

Related

Writing JSON in Classic ASP page, and general (mis)understanding of Http Response

I had a classic ASP page (VBscript) that generates an XML on server-side, and then Response.Writes it. The page had no client side at all.
However I needed to convert it to JSON. Since I could not find an ASP server-side way that worked (whole different subject) I did it on client-side with a Javascript code I found, finally document.writing it to the page.
THE PROBLEM is that the result is not the same: If before the http RESPONSE was only an XML, the response now is the javascript code, which writes to the browser the JSON , but not to the response. Am I understanding this right?
In other words, if before I had an xml as the response, now the response is this:
<script type="text/javascript">
var xmlObj = parseXml('<%=resultXml%>');
var json = xml2json(xmlObj);
document.write(json);
</script>
This whole block is called by the ASP inside a method like this:
sub writeJsonResult(resultXml)
% >
the above javascript is here
< % end sub
% >
So again, visibly the browser shows the JSON, but the service that uses it doesn't get the RESPONSE it needs. Is there a way to write the JSON as response? I feel I am missing something and not quite understanding this.
The service is expecting to get JSON.
You are giving it an HTML document containing client JavaScript that dynamically writes JSON into the page.
You need to give it actual JSON, so you need to find a way to generate that JSON using ASP.
AS #Quentin has pointed out;
The service is expecting to get JSON.
This means trying to get around that by processing the JSON client-side isn't going to work as that would mean you have sent back a text/html HTTP response instead of a application/json one.
There is no getting around it you have to process the XML to build a JSON structure server-side then return it using
Response.ContentType = "application/json"
There are lots of JSON libraries out there for Classic ASP, some good, some great and some just plain awful. You just need to have a look through and see which one suits you, if you are looking for a recommendation ASPJSON.com is probably the most widely used library (but weirdly the site appears to be down at the moment).
If possible where the XML is generated replace this with a JSON using a library like described above, most of them support building JSON structures directly from the database, saving you on parsing and building the JSON from the XML yourself.
Useful Links
Any good libraries for parsing JSON in Classic ASP? [closed]
Classic ASP JSON Class (site currently down)
JSON object class 3.4.1 by RCDMK

text/html output when requesting JSONP

I have been playing around with the jQuery library the last week or two.
Very handy! I am now playing with the AJAX requests to retrieve things such as the weather, current downloads and more, which have been going well so far!
I have now tried to connect up to my ISP to get my current data usage (peak, off peak etc).
When I use Chrome, I can manually type the variables into the URL and have the required JSON code show in the browser. The issue is, that it seems to return text/html instead of application/json.
When you go into developer tools, it shows text/html. This make it difficult for me to retrieve the data from my home server using AJAX and JSONP. See here for a failed query (but you can still see the text/html output, which is in a JSON format! Failed JSON Query on ISP
My question is, how could I get this data from the server URL, then make it into JSON that jQuery can read?
When I try the .load , $.get functions I run into Cross Origin Issues...
EDIT:Here is the PDF documentation for the API (Download at the bottom of the page)
Notice that I need to append certain values (user / pass / token). My ultimate aim is to have my JS read these values and store them.
The issue is, that it seems to return text/html instead of application/json.
That's a serverside issue. Go and file a bug report.
This make it difficult for me to retrieve the data
Not by itself. You should be able to override the settings how responses are parsed, e.g. in jQuery by using the datatype parameter.
using AJAX and JSONP
Notice that you cannot use JSONP, as it is not supported by that API (judging from the docs and a simple ?callback=test try). If you want support for that, file a bug report against the service provider.
When I try the .load, $.get functions I run into Cross Origin Issues...
Yes. They don't send CORS headers either. I suspect that this API is only used internally, and by devices that are not subject to a same-origin policy.
how could I get this data from the server URL, then make it into JSON that jQuery can read?
Use a proxy on your own server (that runs in the same domain as your app). It can also fix that content-type header.
For more details see also Ways to circumvent the same-origin policy, though most of the methods require cooperation of the service provider (to implement serverside features).
If i understand you correctly You ask for a certain value and it gives you a string. For most API's in the world they send a string that you have to parse into JSON or some language code. I would suggest looking at Parsing JSON Strings link. It explains how to take well formated strings and parse them into JSON readable objects.
var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );
if you go on further and start using php take a look that Parsing JSON Strings with PHP
EDIT:
use .done() method to grab text from other pages after AJAX call.
$.ajax(...).done(function(html){
//do what you want with the html from the other page
var object = $.parseJSON(html)
}

Is there an online tool that grabs XML from some remote URL then provides a way to get the data via json using javascript?

Its easy to grab XML directly of your own domain from some local URL, but cross-domain isn't. How would you grab the XML data that is found at http://google.com/complete/search?output=toolbar&q=keep+skat with javascript?
Yes, you can! I would use YQL (Yahoo Query Language) and its pretty simple. You can definitely convert from XML to JSON and also can pass callback function to use along with JSONP.
Please visit YQL console and you can build your query from there.
For your problem, use this REST call (which I used to generate from YQL console):
http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%3D%22http%3A%2F%2Fgoogle.com%2Fcomplete%2Fsearch%3Foutput%3Dtoolbar%26q%3Dkeep%2Bskat%22&format=json&diagnostics=true&callback=myCallbackFunc
Response from this URL will give you the JSON from the XML returned from your URL.

JavaScript, JSONP and reading XML from cross-domain

in my JS project I need to load data from cross-domain. (JavaScript sits on domain A, the data comes from domain B)
I have a solution that uses JSONP but I really need to load an XML instead (ordinary XML music playlist). The main goal is to be able to load and parse the XML data without the need to modify them first to some other format (like JSONP).
Is it completely impossible? Or are there any workarounds or hacks?
I am targeting mainly the latest browsers mainly on iOS.
Thanks!
PS: Could easyXDM be of any help? Or it's not relevant to XMLs?
UPDATE: unfortunately I can not use proxy, I am really asking about a direct solution.
You can totally do this, just have your domain B return something like
func("<myxml></myxml>");
or
var someVar = "<myxml></myxml>";
The name JSONP doesn't really have anything to do with JSON specifically since its concept is all about executing JavaScript that has your data embedded in the code.
Once your domain B returns exactly one of those 2 forms above, domain A can simply use it either by doing:
<script>
function func(xmlString) {
alert(xmlString); // you can parse the xmlString with
// jQuery or something else
}
</script>
or if you use the second example:
<script>
alert(someVar);
</script>
The usual solution is to have a "AJAX proxy" - a simple server-side script running on your domain, that fetches the data from the other domain and returns it unchanged.
The simplist is to give the script the URL you need the data from:
http://example.com/proxy.php?url=http%3A%2F%2Fexample.org%2Fajax%3Fid%3D123 gets the data from http://example.org/ajax?id=123
This can however be misused if you let any URL be fetched like that, so you should have your script, check that it actually only gets data from a specific URL.
In order to avoid having to parse the URL to check this, you could write a proxy specificly for your app, that only accesses the specific resource you need:
http://example.com/proxy.php?id=123 to access http://example.org/ajax?id=123.
If you have a JSON-P solution in place, you can just pass the XML to the JSON-P callback as a string. You can then do XML parsing of a variable string in JavaScript
The whole idea with JSONP is that the response must be executable as script. So sure, you can pass XML data back, as long as it's valid Javascript - for example, the server could wrap its response in a string:
myCallback('<xml><stuff/></xml>')
and you'd have to parse it with jQuery:
success: function(data) {
var xml = $(data); // now do stuff
}
This assumes that you control the other server and/or someone who does is interested in formatting their data that way. Otherwise, you're out of luck, and need a proxy of some sort - you might be able to do this with YQL.

Can you transport a Javascript object to server and receive it in the same state?

I'm considering creating a simple remote debugging application for Javascript. Actually, I want to provide an object to Firebug Lite and let it do all the job.
So, can I get an object from one page, serialize it, send it to server and then to another browser and finally see the same results in Firebug Lite (on that other client) as I would see on the first browser (with doing "console.dir(obj)")? Is it possible to do?
Plain answer: no. You'll have to serialize your object to some kind of string. It could be XML, or JSON, or a format you make up, like:
var anObject = {first:1,second:2,third:'infinite'};
function serializer(obj){
var serialized = [];
for (var l in obj){
if (obj.hasOwnProperty(l)){
serialized.push(l+'='+obj[l]);
}
}
return serialized.join('&');
}
alert(serializer(anObject)); //=>first=1&second=2&third=infinite
If your object contains objects, you could use the serializer function recursively.
Using JSON for encoding the object?
http://json.org/
The easiest solution is to serialize to JSON. However, it is important to note JSON does not support all JavaScript types.
Instead of just half-answering the question, here's the real deal!
Like the others said, use JSON (implementation details) to serialize your data (because it's nativly supported by Javascript and it's lightweight), and then send it to your server using AJAX, maybe by sending it to a PHP script that just saves it to a file or a database or something.
Then on the other side, you simply receive it by again using AJAX to ask said PHP script to return that data to you!

Categories

Resources