Is getting JSON data with jQuery safe? - javascript

JSON allows you to retrieve data in multiple formats from an AJAX call. For example:
$.get(sourceUrl, data, callBack, 'json');
could be used to get and parse JSON code from sourceUrl.
JSON is the simply JavaScript code used to describe data. This could be evaled by a JavaScript interpreter to get a data structure back.
It's generally a bad idea to evaluate code from remote sources. I know the JSON spec doesn't specifically allow for function declarations, but there's no reason you couldn't include one in code and have an unsafe and naive consumer compile/execute the code.
How does jQuery handle the parsing? Does it evaluate this code? What safeguards are in place to stop someone from hacking sourceUrl and distributing malicious code?

The last time I looked (late 2008) the JQuery functions get() getJSON() etc internally eval the JSon string and so are exposed to the same security issue as eval.
Therefore it is a very good idea to use a parsing function that validates the JSON string to ensure it contains no dodgy non-JSON javascript code, before using eval() in any form.
You can find such a function at https://github.com/douglascrockford/JSON-js/blob/master/json2.js.
See JSON and Broswer Security for a good discussion of this area.
In summary, using JQuery's JSON functions without parsing the input JSON (using the above linked function or similar) is not 100% safe.
NB: If this sort of parsing is still missing from getJSON (might have recently been added) it is even more important to understand this risk due to the cross domain capability, from the JQuery reference docs:
As of jQuery 1.2, you can load JSON
data located on another domain if you
specify a JSONP callback, which can be
done like so: "myurl?callback=?".
jQuery automatically replaces the ?
with the correct method name to call,
calling your specified callback.

$.getJSON() is used to execute (rather than using eval) javascript code from remote sources (using the JSONP idiom if a callback is specified). When using this method, it is totally up to you to trust the source, because they will have control to your entire page (they can even be sending cookies around).
From Douglas Crockford site about The Script Tag Hack (jsonp):
So the script can access and use
its cookies. It can access the
originating server using the user's
authorization. It can inspect the DOM
and the JavaScript global object, and
send any information it finds anywhere
in the world. The Script Tag Hack is
not secure and should be avoided.

Both IE 8 and Firefox 3.1 will have native JSON support, which will provide a safe alternative to eval(). I would expect other browsers to follow suit. I would also expect jQuery to change its implementation to use these native methods.

All browsers I know of disable cross-site requests through Ajax. That is, if your page sits on my.example.com, you can't load anything using Ajax unless its URL is also at my.example.com.
This actually can be something of a nuisance, and there are ways for an attacker to inject source in other ways, but ostensibly this restriction is in place to address exactly the concern you mention.

Related

Getting user agent value. Server side vs Client side?

I need to pass user agent value into front end.
I can get this value using $_SERVER['HTTP_USER_AGENT'] and write it into front end.
(Actually I will be using Mage::helper('core/http')->getHttpUserAgent(), but I think it's just a magento helper to call above mentioned function.)
Or I can use get navigator.userAgent with js on client side.
Which better and why? My primary concern is speed.
p.s. I understand that UA can be easily manipulated. We are not basing any serious functionality on the value, it's used as a secondary parameter.
I would personally use navigator.userAgent. Mainly, because passing values from PHP to JavaScript is pretty ugly in my opinion. Also, the value will be exactly the same for both. Even if someone decides to edit their useragent.
I think simplicity takes the cake here.
Performance will depend on the purpose. If you need this inside php, then use the server variable with helper getter you mentioned above. For js use navigator object.
In general both navigator.userAgent and HTTP_USER_AGENT are variables of Request Header and are both already present in memory (of server or users browser in case of js). So no measurable performance difference is possible.

Why use JSONP and callbacks instead of a caller defined variable name?

I understand the idea behind jsonp and I'm sure there is a reason for not doing the following but I am curious as to what that is.
Why (due to security, ease of use, etc.) would one not create an API such as the following?
http://www.something.com/json/?caller_var_name=the_var
returning JavaScript containing:
the_var = {"my": "json", "content": 1};
On the client, the code would look like:
<script>
var the_var;
</script>
<script src="http://www.something.com/json?varname=the_var"></script>
// the_var now contains the requested JSON data
This seems straightforward and I've tested it cross domain but as mentioned, I'm sure those that thought of JSONP had a reason for not doing the above. Why is that?
The point of using a "callback" function is that you get called back. The script does load asynchronously, and when it does get you automatically get your function called - it is as if the JSONP script fires a listener.
Of course, the approach with the variable would work as well, especially for synchronously loading scripts. However, when using asynchronous loading we would need to poll for the variable value being set, or use a DOM event for executing scripts. The former is despised, the latter is (and especially was) complicated because of inconsistent browser apis.
Notice that if you want to do this nonetheless, the common JSONP apis can be used with your "variable style" by putting ?callback=the_var%3D in the URL parameter.
The usual usecase for JSONP doesn't involve hard coding the script element into the page. It dynamically generates the script element on demand.
By using a function, you can perform an action with the data when the script loads.
The alternative would be to insert the script element and then keep polling the global namespace to see if the variable had been populated yet or not.

Returning a Javascript object from server

Apologies for what is most likely an obvious question. In general terms, I would like write a client-side Javascript function that makes a request to my server; this would then return a Javascript object.
This seems to be a common thing, but I'm not entirely sure which techniques I should be using. Do I need to be running something like Node on my server to do this, or am I missing something basic? And is it possible to return a Javascript object directly, or would I return JSON and then convert this client-side into an object?
Googling seems to bring up a vast number of Ajax PHP \ ASP techniques, but I'm just using javascript.
Thank you very much in advance, and please do accept my apologies if it's a dense question.
The server would return JSON and JSON is javascript in object notation. The difference between JSON and a javascript object, is that JSON is a standard and has strict requirements, for example that property names and values are wrapped in double quotes.
You don't need a special server to return JSON. JSON is should be treated like XML or any other data format.
Returning JSON from a server is best done with JSONP if you want to avoid cross site scripting issues. You can read more about JSONP on
http://json-p.org/
http://remysharp.com/2007/10/08/what-is-jsonp/ and
What is JSONP all about?
Either way, JSONP or JSON and Ajax, you'll need to make sure your JSON is valid and the correct headers are sent.
Content-Type: application/json
if you send request to server, the application running at server will send back some data to browser, Json,XML,HTML, etc. what you should know is the data returned by server may have many types.
if you have no idea about the application in server, i suggest you can write some code running at server by using nodejs. in this way you do not have to study another language like php,java,python.
Loading a javascript from the server via AJAX/PHP as a kind of dynamic plug-in to the current page is an obvious technique to keep code in the page small and maintainable (and generic ...?)
I use jQuery.getScript for this. It has a callback function which will be executed when the code is loaded an has been initially run. Just look at http://api.jquery.com/jQuery.getScript/

How to pass javascript object from one page to other

I want to pass javascript object from one page to other page so anyone can tell me how to do it?
Is that possible to do so using jQuery?
Few ways
Server side postback
Have a POST form on your page and save your serialized object inside a hidden input then post it to the other page. You will be able to process that data on the server and most likely put it back somehow into the page. Either as javascript object or anything else.
Client side URL examination
Make a GET request to your other page by attaching your serialized object to URL as:
http://www.app.com/otherpage.xyz?MyObject=SerializedData
That other page can then easily parse its URL and deserialize data using Javascript.
What's in a window.name = local cross-page session
This is a special technique that's also used in a special javascript library that exposes window.name as a dictionary, so you can save many different objects into it and use it as local cross-page-session. It has some size limitations that may affect you, but check the linked page for that and test your browsers.
HTML5 local storage
HTML5 has the ability of local storage that you can use exactly for these purposes. But using it heavily depends on your browser requirements. Modern browsers support it though and data can be restored even after restarting browsers or computers...
Cookies
You can always use cookies but you may run into their limitations. These days cookies are not the best choice even though they have the ability to preserve data even longer than current window session.
Javascript object serialization
You will of course have to use some sort of a (de)serializer on your client side in some of the upper cases. Deserializers are rather easy to find (jQuery already includes a great function $.getJSON()) and are most likely part of your current javascript library already (not to even mention eval()).
But for object to JSON string serialization I'd recommend json2.js library that's also recommended by John Resig. This library uses in-browser implemented JSON (de)serialization features if they exist or uses it's own implementation when they don't. Hence recommendation.
That is only possible if the pages exist at the same time, and one page is opened from the other so that you have a reference to the other pages windows object.
If you navigate from one page to another, they don't exist at the same time, so you can't communicate like that. You would have to serialise the object into a string that you can send along in the request, for example sending JSON in the query string.
There are different ways of persisting data, like in the query string, post data, cookies, window name or HTML5 local storage, but all those methods can only persist string values, not Javascript objects.
This is possible to do, and you have a couple of options.
Local Storage
Can be added/eddited/removed at any stage and accessed across a domain. (doesn't work natively in ie6 and ie7 however there are work arounds for that)
The Window Object
I would put a massive cavet around this not being the best solution, it's not at all secure, so only use it for things that don't need to be kept private. window.name = { "json" : "object"} which is then available in the following page in the window.name property.
I believe that the only way to pass a javascript object from one page to another is to serialize it into string and pass it in url. For example if you have object
var temp = { id: 1, value: 'test' }
you may want to use JSON-js to serialize it and pass it in for example http://mysite.com/?data=serialization. Then after you load the page you need to deserialize it via for example $.parseJSON().
If your application uses sessions, you could serialize it (as per other answers) then POST it to the server where it is stored in a session variable. In the next page, you retrieve it from the session variable.
In Javascript, normally all variables only exist in a scope that is unique to that page load. They don't persist between different pages if there is a new page load.
The exceptions to this are
Cookies.
Local storage.
Cookies are truly cross-browser but are extremely limited in terms of size. You shouldn't expect to be able to store more than 4kB of cookies for a page reliably; in fact you probably shouldn't be using any more than 1kB. Cookie data slows down the loading of every page and other request, so it should be used sparingly.
There are various types of local storage available to Javascript, but the only practical cross-browser implementation of this is HTML5 webstorage which is implemented in all modern browsers (IE8+, FF, Chrome, Safari, etc), but is notably not implemented in IE6 or IE7, if that matters.
Both these approaches store a value in the user's browser which can be made to be persistent so that it can be written to and read from by pages from the same site, even between page views (and even, often, between browser sessions or computer reboots).
I wrote a library some time ago, that can store most js objects to localstorage. For example instances of your prototype classes, with references to other objects, self references included. Bare in mind that IE support is lackluster.

Actionscript3 to JavaScript communication: best practices

On a more abstract level then a previous question, in my experience there are 3 ways to call a javascript function on an html page from an embedded .swf using AS3: ExternalInterface, fscommand, and navigateToURL.
Let's compare and contrast these methods (and maybe others I haven't listed) and talk about the pros and cons of each - right now, ExternalInterface seems like the way to go in terms of flexibility, but is it right for all situations? Are there concrete benefits in terms of execution speed or anything like that? I'm curious - what do we think?
ExternalInferface was created to make communication between JS and Flash easier, so it doens't really make sense to use anything else. Common practice is to check if its available first by evaluating the value of the ExternalInterface.available property before making a call to some JS. This property tells you if the SWF in which you want to call some JS from is inside a container that offers an external interface. In otherwords, if using ExternalInterface will work. If its not available then just use flash.net.sendToUrl. Never use fscommand() as it uses VBScript and can cause conflicts with other VBScript on a page. Additionally, you can only send one argument string with fscommand and have to split it on the JS side.
It all depends on if you want the communication to be synchronous or not as ExternaInterface can return data as where navigatoToURL and fscommand are asynchronous and can only call a javascript function; they cannot return values or a response.
From live docs in relation to External Interface:
From ActionScript, you can do the following on the HTML page:
Call any JavaScript function.
Pass any number of arguments, with any names.
Pass various data types (Boolean, Number, String, and so on).
Receive a return value from the JavaScript function.
From JavaScript on the HTML page, you can:
Call an ActionScript function.
Pass arguments using standard function call notation.
Return a value to the JavaScript function.
The flash.external.ExternalInterface class is a direct replacement for the flash.system.fscommand class.
So using ExternalInterface is the preferred method or communication between flash and a Javascript function, though if the call is merely Asynchronous it is ok to use flash.net.navigateToURL.
ExternalInterface
You can get the return value from JS-AS and AS-JS calls
Encodes your arguments (call with arrays, objects, etc. No need to encode them)
Cross browser
Flawed when you send HTML or JSON (special encoding), it breaks internally
getURL
You can only call JS, you not get the return value and you need to encode your data
Was nice than deprecated and in Flash 10 it's removed
It is really removed, so don't use it ;)
fscommand
Come on, ExternalInterface is the solution (for 2008).

Categories

Resources