What is the difference between AJAX, RESTful/Rest, JSON and JSONP? - json

I am just confused with the these terms. Can anybody please provide/explain me brief with an example?

Ajax - "Asynchronous Javascript and XML". Ajax loosely defines a set of technologies to help make web applications present a richer user experience. Data updating and refreshing of the screen is done asynchronously using javascript and xml (or json or just a normal http post).
JSON - "Javascript Object Notation". JSON is like xml in that it can be used to describe objects, but it's more compact and has the advantage of being actual javascript. An object expressed in JSON can be converted into an actual object to be manipulated in javascript code.
By default, Ajax requests have to occur in the same domain of the page where the request originates. JSONP - "JSON with padding" - was created to allow you to request JSON resources from a different domain. (CORS is a newer and better alternative to JSONP.)
REST - "Representational State Transfer". Applications using REST principles have a Url structure and a request/response pattern that revolve around the use of resources. In a pure model, the HTTP Verbs Get, Post, Put and Delete are used to retrieve, create, update and delete resources respectively. Put and Delete are often not used, leaving Get and Post to map to select (GET) and create, update and delete (POST)

Ajax, or more properly, AJAX, stands for Asynchronous Javascript And Xml. Technically it refers to any asynchronous request made by the browser (anything that uses an XmlHttpRequest) on behalf of some script running on the current page, regardless of what content-type is returned. It can also be used to describe a certain pattern of constructing a page/site where most/all of the content is fetched/updated dynamically on the page. When used to describe a data format, "ajax" typically means "xml".
JSON is a data encoding format. The name itself is an acronym for "JavaScript Object Notation". JSON-formatted data looks like:
{"key": "value1", "key2": {"number": 1, "array": [0, 1, 2]}}
JSON data may be fetched by an AJAX request, though it is quite commonly used in other contexts as a lightweight, extensible, and easy-to-parse data exchange format.
JSONP is simply JSON-formatted data wrapped in a callback function. The "P" stands for "with Padding", which is kind of stupid unless you like to think of function calls as "padding". In any case, JSONP data will look like:
someFunction({"key": "value1", "key2": {"number": 1, "array": [0, 1, 2]}});
As such, JSONP is really just a JavaScript snippet, and unlike JSON is not used outside of the context of JavaScript, browsers (or other JavaScript-capable clients), and AJAX requests. The reason for using JSONP is that it allows the same-origin policy to be subverted. A script that was sourced in from site X cannot make a direct request to site Y if site Y is on a different domain from site X. But if site Y's server can send JSONP-formatted responses, then the script from site X can add a new <script> tag to the document that references a URL on site Y, and when the response from site Y is loaded it will invoke some callback function that script X has defined in the document, thus giving script X access to data that was loaded dynamically from site Y.
Note that JSONP data is not (typically) requested using an XmlHttpRequest. It can be done this way, subject to the standard caveats of the same-origin policy, but then you lose the cross-domain magic that makes JSONP useful in the first place.
REST is simply the formal spec/description of how HTTP actually works/is intended to be used. If you understand the concept of a URL being used to request a corresponding resource from a server and the difference between Get and Post then you really know all you need to about REST.

Ajax stand for Asynchronous JavaScript and Xml/XhttpRequet (the X depends and changed since mostly json is used today.
It's a way to execute a request from the page using javascript to the server and receive some response. This response can be anything, json, xml, text, html, etc...
This makes pages look very responsive without having to reload the complete page to execute actions on it. For example posting this answer to your questions. :-)
Json is a data format stands for JavaScrip Object Notation. It's a lighter serialization format than xml and has the advantage to be JavaScript.
JsonP is the next and logical step to using Ajax with Json.
A server will response with JSONP wrapping the Json object in a callback function. The name of the function is passed by the client to the server, usually as a parameter in the querystring.
The P stands for padding, since the server surrounds the json object with the name of the function and the object as an argument.
callback({"name":"my name"});
See: http://en.wikipedia.org/wiki/JSONP for a more detailed explanation.

Related

FOSRestBundle - is a good practice to inject body params in the parameter bag?

We are using the FOS Rest bundle, and, at first, we were unaware that the body listener was active.
In the meanwhile, we created a lot of resources that are receiving data via the body, in JSON format. For now we only support JSON format. Lot of them now in the controllers are retrieving parameters from the Symfony ParameterBag, because, body listener was injecting them there.
So, do you think is a good practice to leave to body listener the responsibility of that, and in the controllers retrieve parameters via the parameter bag? This way, no matter via GET, POST or body, all the parameters arrive to the controllers via parameter bag.
We are looking at this because some of our API clients were making requests without providing the content-type in the header, and because of that, body listener didn't inject the body in the parameter bag. So in the controllers we didn't have the parameters available.
Thanks in advance!
Generally speaking, one of the most important aspects of API design should be consistency across your implementation, so that your consumers understand how to interact with your system. To that end, I would follow this pattern:
Keep the body listener enabled if it assists with your development; this listener is a shortcut to help you write simpler controllers, so if it is working for you, there's no reason to abandon it
For API endpoints that expect a JSON request body, report to the consumer that they are making an illegal request if the proper Content-type: application/json header is missing (which can be done via setting a _format requirement on the route; see advanced routing example)
If you must support these legacy users that are not passing the header, you could create a listener on the kernel.request event with a very high priority which simply checks for the detected mime type and, and if it is missing, does something like this:
if ($request->getRequestFormat() != 'json') {
json_decode($request->getContent());
if (json_last_error() == JSON_ERROR_NONE) {
$request->setRequestFormat('json');
}
}
(The use of json_last_error() is not perfect here; see this question for a more detailed discussion.)
Finally, if you aren't already, make sure that you are restricting your API controllers to the proper request method, again to make sure that they are being consumed correctly and to make your development and use more consistent. If you are using annotations, for example, this is as simple as using the FOSRestBundle-provided #Get, #Post, etc. in place of the usual #Route. If you are using YML or XML configuration, it's the methods property.
Although it is certainly possible for a single controller to accept data via a GET (with request parameters), a POST (via URL-encoded form data), or a POST or PUT with JSON data and a body listener-conversion, this makes for a very convoluted API, as you have to start maintaining these different cases, and I would argue that things become very difficult for your users as well.
As a consumer of these APIs, I would expect my requests to fail if I were passing JSON in a request body but not including the proper header, and I would expect my requests to fail if I were passing x-www-form-urlencode data to a JSON-based API. Overall, both for the maintainer of an API and for the consumers, it is a good idea to be strict on what you accept and to follow the same pattern throughout.

What http verb to use to send JSON in body?

I have a UI in my webapp that allows users to build fairly complex charts where they can specify chart types, chart axes, ranges, and also specify multiple filters (which can be quite complex themselves). I've written the javascript (actually CoffeeScript) in a very OO style, so that the whole state of the chart configuration can be serialized to a very neat and tidy JSON document. When the user wants to render the graph, a request is made to the server with that JSON document in the request body, and the server then responds with another JSON document containing the actual data for the chart.
My question is, what HTTP verb should I be using for this request? I'm currently using POST as a GET request with a body feels wrong, but POST doesn't really fit. Any ideas would be helpful!
What makes you feel POST does not fit?
As GET utilizes the querystring via a parameterized / key value pairing, adding the json as one qs value would not feel right to me, where as a POST feels absolutely the right choice.

JSON vs Form POST

We're having a bit of a discussion on the subject of posting data to a REST endpoint. Since the objects are quite complex, the easiest solution is to simply serialize them as JSON and send this in the request body.
Now the question is this: Is this kosher? Or should the JSON be set as a form parameter like data=[JSON]? Or is sending of JSON in the request body just frowned upon for forcing the clients using the application, to send their data via JavaScript instead of letting the browser package it up as application/x-www-form-urlencoded?
I know all three options work. But which are OK? Or at least recommended?
I'd say that both methods will work well
it's important that you stay consistent across your APIs. The option I would personally choose is simply sending the content as application/json.
POST doesn't force you to use application/x-www-form-urlencoded - it's simply something that's used a lot because it's what webbrowsers use.
There is nothing wrong about sending it directly as serialized JSON, for example google does this by default in it's volley library (which obviously is their recommended REST library for android).
If fact, there are plenty of questions on SO about how not to use JSON, but rather perform "normal" POST requests with volley. Which is a bit counter intuitive for beginners, having to overwrite it's base class' getParams() method.
But google having it's own REST library doing this by default, would be my indicator that it is OK.
You can use JSON as part of the request data as the OP had stated all three options work.
The OP needs to support JSON input as it had to support contain complex structural content. However, think of it this way... are you making a request to do something or are you just sending what is basically document data and you just happen to use the POST operation as the equivalent of create new entry.
That being the case, what you have is basically a resource endpoint with CRUDL semantics. Following up on that you're actually not limited to application/json but any type that the resource endpoint is supposed to handle.
For non-resource endpoints
I find that (specifically for JAX-RS) the application/x-www-urlencoded one is better.
Consistency with OAuth 2.0 and OpenID Connect, they use application/x-www-urlencoded.
Easier to annotate the individual fields using Swagger Annotations
Swagger provides more defaults.
Postman generates a nice form for you to fill out and makes things easier to test.
Examples of non-resource endpoints:
Authentication
Authorization
Simple Search (though I would use GET on this one)
Non-simple search where there are many criteria
Sending a message/document (though I would also consider multipart/form-data so I can pass meta data along with the content, but JAX-RS does not have a standard for this one Jersey and RestEasy have their own implementations)

What does the 'P' in JSONP stand for?

I can't seem to find a definitive answer on this -- what does the p in JSONP stand for?. The candidates I've found so far are padding and prints. Anyone know where the JSONP name came from?
Padding.
from http://en.wikipedia.org/wiki/JSONP
JSONP or "JSON with padding" is a complement to the base JSON data
format, a pattern of usage allowing a page to request data from a
server in a different domain. JSONP is a solution to this problem,
forming an alternative to a more recent method called Cross-Origin
Resource Sharing.
Padding
While the padding (prefix) is typically the name of a callback
function that is defined within the execution context of the browser,
it may also be a variable assignment, an if statement, or any other
Javascript statement. The response to a JSONP request (namely, a
request following the JSONP usage pattern) is not JSON and is not
parsed as JSON; the returned payload can be any arbitrary JavaScript
expression, and it does not need to include any JSON at all. But
conventionally, it is a Javascript fragment that invokes a function
call on some JSON-formatted data.
Said differently, the typical use of JSONP provides cross-domain
access to an existing JSON API, by wrapping a JSON payload in a
function call.
Hope that helped. Google wins!
Stone,
What I know, it stands for 'Padding'. There is a explaination about it on Wikipedia: JsonP
What it does?
It gives you the possibility to make a CROSS-DOMAIN request and get JSON data returned.
Normally via the HTML script tag you call for another JavaScript.
But JsonP provide you a callback function and you can return noraml Json response.
Example:
You create a script tag:
<script type="text/javascript" scr="http://anotherDomain/Car?CarId=5&jsonp=GiveCarResponse"></script>
In this script the GiveCarResponse is the callback function on the other Domain. Invoking this function will result in a Json response. In example:
{"CarId":5, "Brand":"BMVV", "GAS": false}
Does this make sense?
From wikipedia, it stands for "padding" (or with padding).
http://en.wikipedia.org/wiki/JSONP
Umm ... you've seen the wikipedia page, and you mistrust its accuracy?
This standards site seems to confirm the "with padding".
It basically means to add a calling function around JSON.
AJAX can be called from your own server only and is not a cross domain. So to load data from different servers at client side, you make a JSONP request, basically you load a normal javascript file from other server just like you include a normal javascript file. Bust as JSON is not a valid javascript file, JSON is wrapped up in a function call to make it valid js file. the wrapped up function (already in your code) then extracts that data and show it on your page.

Using MVC3's AntiForgeryToken in HTTP GET to avoid Javascript CSRF vulnerability

In regards to this Haacked blog, I'm hesitant to implement the proposed anti-JSON GET hijacking solutions since
The recommended solutions to mitigating JSON hijacking involve non-REST-full JSON POSTs to GET data
The alternate solution (object wrapping) causes problems with 3rd party controls I don't have source-code access to.
I can't find a community-vetted implementation that implements the Alternative Solution (listed below) on how to compose the security token, or securely deliver it within the webpage. I also won't claim to be enough of an expert to roll my own implementation.
Referrer headers can't be relied upon
Background
This blog describes a CSRF issue regarding JSON Hijacking and recommends using JSON POSTs to GET data. Since using a HTTP POST to GET data isn't very REST-full, I'd looking for a more RESTfull solution that enables REST actions per session, or per page.
Another mitigation technique is to wrap JSON data in an object as described here. I'm afraid this may just delay the issue, until another technique is found.
Alternative Implementation
To me, it seems natural to extend the use ASP.NET MVC's AntiForgeryToken with jQuery HTTP GETs for my JSON.
For example if I GET some sensitive data, according to the Haacked link above, the following code is vulnerable:
$.getJSON('[url]', { [parameters] }, function(json) {
// callback function code
});
I agree that it isn't RESTfull to GET data using the recommended POST workaround. My thought is to send a validation token in the URL. That way the CSRF-style attacker won't know the complete URL. Cached, or not cached, they won't be able to get the data.
Below are two examples of how a JSON GET query could be done. I'm not sure what implementation is most effective, but may guess that the first one is safer from errant proxies caching this data, thus making it vulnerable to an attacker.
http://localhost:54607/Home/AdminBalances/ENCODEDTOKEN-TOKEN-HERE
or
http://localhost:54607/Home/AdminBalances?ENCODEDTOKEN-TOKEN-HERE
... which might as well be MVC3's AntiForgeryToken, or a variant (see swt) thereof. This token would be set as an inline value on whatever URL format is chosen above.
Sample questions that prevent me from rolling my own solution
What URL format (above) would you use to validate the JSON GET (slash, questionmark, etc) Will a proxy respond to http://localhost:54607/Home/AdminBalances with http://localhost:54607/Home/AdminBalances?ENCODEDTOKEN-TOKEN-HERE data?
How would you deliver that encoded token to the webpage? Inline, or as a page variable?
How would you compose the token? Built in AntiforgeryToken, or by some other means?
The AntiForgeryToken uses a cookie. Would a backing cookie be used/needed in this case? HTTP Only? What about SSL in conjunction with HTTP Only?
How would you set your cache headers? Anything special for the Google Web Accelerator (for example)
What are the implications of just making the JSON request SSL?
Should the returned JSON array still be wrapped in an object just for safety's sake?
How will this solution interop with Microsoft's proposed templating and databinding features
The questions above are the reasons I'm not forging ahead and doing this myself. Not to mention there likely more questions I haven't thought of, and yet are a risk.
The Asp.net MVC AntiForgeryToken won't work through HTTP GET, because it relies on cookies which rely on HTTP POST (it uses the "Double Submit Cookies" technique described in the OWASP XSRF Prevention Cheat Sheet). You can also additionally protect the cookies sent to the client by setting the as httponly, so they cannot be spoofed via a script.
In this document you can find various techniques that can be used to prevent XSRF. It seems the you described would fall into the Approach 1. But we have a problem on how to retrieve the session on the server when using Ajax HTTP GET request since the cookies are not sent with the request. So you would also have to add a session identifier to you action's URL (aka. cookieless sessions, which are easier to hijack). So in order to perform an attack the attacker would only need to know the correct URL to perform the GET request.
Perhaps a good solution would be to store the session data using some key from the users SSL certificate (for example the certs thumb-print). This way only the owner of the SSL certificate could access his session. This way you don't need to use cookies and you don't need to send session identifiers via query string parameters.
Anyway, you will need to roll out your own XSRF protection if you don't want to use HTTP POST in Asp.net MVC.
I came to this problem and the solution was not so trivial however there is a fantastic blog to get you started this can be used with get and post ajax.
http://johan.driessen.se/posts/Updated-Anti-XSRF-Validation-for-ASP.NET-MVC-4-RC
If you place the following in the global name space all your post/gets can take advantage having an anti forgery token and you don't have to modify your ajax calls. Create an input element in a common page.
<form id="__AjaxAntiForgeryForm" action="#" method="post">#Html.AntiForgeryToken()</form>
The following javascript will read the anti forgery tokken and add it to the request header.
// Wire up the global jQuery ajaxSend event handler.
$(document).ajaxSend(namespace.ajax.globalSendHandler);
// <summary>
// Global handler for all ajax send events.
// </summary>
namespace.ajax.globalSendHandler = function (event, xhr, ajaxOptions) {
// Add the anti forgery token
xhr.setRequestHeader('__RequestVerificationToken', $("#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]").val());
};
I think it is legitimate to use AntiforgeryToken (AFT) within an ajax http GET request provided that it is embedded in a form that already provides the AFT and associated cookie. The ajax handler can then do the validate on the server just how it would in a normal form post.