What is the difference between JSON and AJAX with jQuery? - javascript

I've heard that JSON serializes all the data, which stops me having problems client side in terms of cross-browser support etc..
I've been using AJAX with jQuery and it seems easy, but I'm unsure of the differences,
I've read I can also use this to get the data:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
Can anyone explain the difference between making a jQuery AJAX request using JSON and making a jQuery AJAX request without the json type?
Will the answer be ok for all browsers?

I think you are confusing the terms.
AJAX stands for Asynchronous Javascript and XML, which is a mechanism used to launch asynchronous HTTP requests to a server using JavaScript. Don't let the name fool you; there's no restriction on you only retrieving JavaScript or XML from this technique. You can quite happily return other data formats as well (HTML, plain text and JSON, to list a few).
JSON is just one of these formats. It's a data interchange format, where-as AJAX is a technique to communicate with a server after the initate page load has completed.
To answer your question on whether you need to specify the dataType; jQuery will best guess the response format (be it HTML or JSON etc), so you're usually fine to omit it.

The dataType option simply changes what type of data jquery should expect from the server. It can be json, jsonp, html, text, xml, or any custom datatype that you define a converter for. They all work in all browsers.
By default jQuery will try to detect what type of data is being returned if you do not supply a dataType option, however I find that it doesn't automatically detect very well.
Edit:
but what if i need to return an object? is basically the answer of a database consult... is it better to use json or only jquery?
You can return an object in the form of html, xml, json, or jsonp. As long as it is in one of those formats, jQuery will be able to interpret it.

JQuery: It is a light weight Javascript Library.
JSON - Stands for JavaScript Object Notation.
Jquery:It is created using JavaScript and you will be using the inbuilt functionalities from the library.
Json: JSON is a text format that is completely language independent.
JQuery:It is a fast and minified JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.
Json: If you want assign data to Your grid then it is possible with Json.

Related

Is there any way to do a non-Ajax form submission with pure JSON data, with jQuery?

I was able to find this old question, which offered a consolation prize that I may end up using: if you want to feed JSON to the server on a POST whole page update, you are able to assign the JSON content to a (perhaps hidden) input.
However, I wanted to check in as far as reality checks go. jQuery has, as a basic and straightforward feature to offer, the ability to call jQuery.ajax() with, as one major option, a JSON string sent as the query string. And it's almost a non-option to fail to provide this functionality; people have come to expect to be able to provide pure-JSON data either way including contexts unrelated to the web and between two non-JavaScript endpoints.
Is there a non-workaround way now to do a page submit with the query string being neither more nor less than whatever JSON string encodes what the developer is sending?

Parsing "Streaming" JSON

I have a grid in a browser.
I want to send rows of data to the grid via JSON, but the browser should continuously parse the JSON as it receives it and add rows to the grid as they are parsed. Put another way, the rows shouldn't be added to the grid all at once after the entire JSON object is received -- they should be added as they are received.
Is this possible? Particularly using jQuery, Jackson, and Spring 3 MVC?
Does this idea have a name? I only see bits of this idea sparsely documented online.
You can use Oboe.js which was built exactly for this use case.
Oboe.js is an open source Javascript library for loading JSON using streaming, combining the convenience of DOM with the speed and fluidity of SAX.
It can parse any JSON as a stream, is small enough to be a micro-library, doesn’t have dependencies, and doesn’t care which other libraries you need it to speak to.
You can't parse incomplete or invalid JSON using the browser's JSON.parse. If you are streaming text, it will invariably try and parse invalid JSON at some point which will cause it to fail. There exists streaming JSON parsers out there, you might be able to find something to suit your needs.
Easiest way in your case would remain to send complete JSON documents for each row.
Lazy.js is able to parse "streaming" JSON (demo).
Check out SignalR.
http://www.hanselman.com/blog/AsynchronousScalableWebApplicationsWithRealtimePersistentLongrunningConnectionsWithSignalR.aspx
March 2017 update:
Websockets allow you to mantain an open connection to the server that you can use to stream the data to the table. You could encode individual rows as JSON objects and send them, and each time one is received you can append it to the table. This is perhaps the optimal way to do it, but it requires using websockets which might not be fully supported by your technology stack. If websockets is not an option, then you can try requesting the data in the smallest chunks the server will allow, but this is costly since every request has an overhead and you would end up doing multiple requests to get the data.
AFAIK there is no way to start parsing an http request before it's finished, and there is no way to parse a JSON string partially. Also, getting the data is orders of magnitude slower than processing it so it's not really worth doing.
If you need to parse large amounts of data your best bet is to do the streaming approach.

packing tree-like structures into a cookie

I would like to be able to store a tree-like structure in a cookie. Ideally, I would like to have something that easily serealizes/deserializes a javascript plain object.
JSON might be a good option, but a quick googling did not filtered out a mainstream approach how to serialize to JSON from JavaScript.
What is the best way to approach the problem?
UPD
Related questions bubbled up Javascript / PHP cookie serialization methods?, which suggests using Prototype's Object.toJSON. I would prefer to stay with jQuery.
UPD2
It turned out that window.JSON.stringify might actually suffice in my case, but mentioned Douglas Crockford's library seems like a good fallback to support browsers where JSON property of the global object is not present.
JSON is your friend.
A free and recognized implementation made by Douglas Crockford is available here
I have used this method to read and store to HTML5's local storage without any problems.
JSON is undoubtedly a good option. To have it work cross-browser include this file in your page https://github.com/douglascrockford/JSON-js/blob/master/json2.js. Then use JSON.stringify() to convert to a string and store, and JSON.parse() to retrieve the object from the cookie.
Be aware that there can be quite low character limits on a single cookie's length, which any jsonified tree could hit, so you might want to preprocess your data before converting to JSON (e.g. replacing booleans with 1's and 0's, switching property names for abbreviated versions) and post-process to reverse these changes after retrieveing from your cookie.
If the amount of data you're storing is really large it may be better to store a session/identifier cookie which is used to retrieve the data from the server via an ajax request (or if you need a quick response on page load, output the data into a script tag) and save the data directly to the server via ajax requests instead of using a cookie.
One more JSON serialization implementation as a jQuery plugin: http://code.google.com/p/jquery-json/

JSON or XML or other data format with jQuery ajax()?

For a data send, where the return data contains potential updates for hundreds of elements on a page, is XML or JSON or another data format better, for usage with jQuery's various parsing formats (invoked via ajax() success)?
Check out this article, it outlines various pros/cons of XML, JSON and HTML when processing AJAX requests.
Personally I'd pick JSON as it uses less bandwidth & is easier to parse and use.
It sounds like a lot of data being returned so json. It's lighter and more compact. Plus it has native use instead of having to parse the xml and traverse it afterwards.
In javascript it is better to go with JSON because it is easier to code and less data to load from the server, unlike XML you have to write a code to parse the elements and fetch the values to your object and for every change in data tags or elements in XML you will need to modify your javascript code which means more coding and testing, unlike JSON all what you need is eval() and you are ready to go.

Should I use JSON or AJAX for response data?

Why JSON? I have done some tests today, and the request time for both JSON, or a normal AJAX request was the same. In the "normal request" I have returned the complete text+html tags, in the JSON request, logically I returned a "json return type" and I have created the HTML with client-side JavaScript.
I don't get it, why are the big sites (Google Reader etc), or even small sites using JSON? Or do I not understand when I should use JSON?
You are perhaps a little confused.
JSON and AJAX are not an either-or choice.
JSON and XML is a choice.
JSON and AJAX are distinct and largely unrelated, although AJAX often uses JSON, it can just easily use XML, HTML or plain text.
Or are you referring to the X in AJAX (XML)? If so, the arguments for JSON are basically:
JSON has a smaller payload than equivalent XML; and
JSON is easier to deal with in Javascript (compare eval'ing a JSON object to walking an XML fragment).
Other than that, it's largely personal preference.
JSON is just a data-interchange format. It describes in what way the data is represented during transmission. You can not replace Ajax with JSON.
Ajax stands for Asynchronous JavaScript and XML, but when using JSON you could say that you're using AJAJ (Asynchronous JavaScript and JSON).
Maybe you are thinking of the jQuery methods $.getJSON() and $.get()?
The difference is that $.getJSON() automatically assumes that it's JSON data, while $.get() will just fetch the data as plain text.
When using $.getJSON() you're also able to fetch data between domains.

Categories

Resources