Before moving to the JSON, AJAX, Jquery with ASP.NET MVC 4 example we need to set up visual studio environment.
Open new Project, under web category select ASP.NET MVC 4 web application. Set name and save location and after that click OK, another window is visible. Select Intranet Application and view engine is Razor, click OK.
Now we need to update existing script libraries and add new script libraries.
Open package manager console. Using the following command install one by one,
- Install-Package jQuery
- Install-Package bootstrap -Version 3.3.5
- Install-Package Newtonsoft.Json -Version 7.0.1
Note: If you want to learn more about the Nuget, Packager manager console and set up visual studio MVC developing environment follow this tutorial.
Now you ready to go with the example.
JSON: JavaScript Object Notation
JSON is a lightweight text-based data-interchange format. Also it is language independent. You can use it php, PERL, Python, Ruby, C#, ext.
The JSON filename extension is .
json.
JSON uses JavaScript syntax,
Why JSON
Before JSON comes use XML. Using XML is hard because XML has to be parsed with an XML parser, so to do that developer need to define XML parser separately. But when JSON comes it is very much easy to deal because JSON can be parsed by a standard JavaScript function. No more need of data parses. It provide us a human-readable collection of data that we can access in a really logical manner.
Also JSON is quicker to read and write and we can use arrays in JSON.
JSON - DataTypes
- A number (integer or floating point)
- var jsonObj = {marks: 92}
- A string (in double quotes)
- var jsonObj = { firstName: 'kamal'}
- A Boolean (true or false)
- var jsonObj = { isHoliday : true }
- An array (in square brackets)
- var jsonObj = '{ "employees":[
- {"firstName":"kamal", "age":"21"},
- {"firstName":"Aruna", "age":"25"},
- {"firstName":"Peter","age":"18"} }';
- ]
- An object (in curly braces)
- var jsonObj = {"firstName":"Sunil", "age":"20"}
- null
Json commonly using to read data from a web server, and display the data in a web page.
The JavaScript function JSON.parse(text) can be used to convert a JSON text into a JavaScript object:
- var JavaScriptObj = JSON.parse(jsonObj);
Mostly JSON using with AJAX [Asynchronous JavaScript and XML].
Ajax: [Asynchronous JavaScript and XML.]
AJAX is a technique for creating fast and dynamic web pages.
Normally after reloading the webpage update their content. But AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes.
In AJAX technology “XMLHttpRequest object” is the core part. Using XMLHttpRequest API exchange the data with a server behind the scenes without having to reload the web page.
Ajax requests are triggered by JavaScript code. Your code sends a request to a URL, and when it receives a response, a callback function can be triggered to handle the response. Because the request is asynchronous, the rest of your code continues to execute while the request is being processed, so it's imperative that a callback be used to handle the response.
According to my example request URL like this [ASP.NET MVC].
Google Maps, Gmail, YouTube and Facebook update the part of the web page without having to reload the entire page.
How AJAX Works
Ajax Events
There are two types of events:
- Local Event
These are events that you can subscribe within the Ajax request object.
- Global Event
These events are triggered on the document, calling any handlers which may be listening.
ajaxStart() :: Global Event
Initially Ajax request before send out to the backend, jQuery checks currently if there are any Ajax requests progressing. if no request found only the ajaxStart() method will execute.
- $( document ).ajaxStart(function() {
-
- });
In the example when an Ajax request starts it can show Loading message to the user.
ajaxSend () :: Global Event
Whenever an Ajax request is about to be sent, jQuery triggers the
ajaxSend event. Any and all handlers that have been registered with the .ajaxSend() method are executed at this time.
- $( document ).ajaxSend(function() {
-
- });
In the example show a message before an Ajax request is sent.
beforeSend ()
This is triggered before an Ajax request is started and allows user to modify the XMLHttpRequest object.
ajaxSuccess () :: Global Event
This event is also called if the request was successful (No errors from the server, no errors with the data).
This will fire for every ajax call success, not just the one.
- $.ajaxSuccess(function(){
-
- });
success () ::Local Event
Only fired within the local ajax call function.
success: function(){/* do local here */});
ajaxError ()
This event behaves the same as the local error event.
error () :: Local Event
This event only fires if an error occurred with the request. Using the following function can get error message when AJAX call failed.
- function getErrorMessage(jqXHR, exception)
- {
- var msg = '';
- if (jqXHR.status === 0)
- {
- msg = 'Not connect.\n Verify Network.';
- }
- else if (jqXHR.status == 404)
- {
- msg = 'Requested page not found. [404]';
- }
- else if (jqXHR.status == 500)
- {
- msg = 'Internal Server Error [500].';
- }
- else if (exception === 'parsererror')
- {
- msg = 'Requested JSON parse failed.';
- }
- else if (exception === 'timeout')
- {
- msg = 'Time out error.';
- }
- else if (exception === 'abort')
- {
- msg = 'Ajax request aborted.';
- }
- else
- {
- msg = 'Uncaught Error.\n' + jqXHR.responseText;
- }
- $('#post').html(msg);
- }
Instead of using this you can also view this in your own browser console, by using console.log inside the error function like:
- error: function (jqXHR, exception) {
- console.log(jqXHR);
- }
More information
demo
ajaxComplete () :: Global Event
This event behaves the same as the complete event and will be triggered every time an Ajax request finishes.
- $(document).ajaxComplete(function() {
-
- });
http://www.pureexample.com/jquery/ajax-complete.html
In example show a message when an Ajax request completes.
complete () :: Local Event
This event is called regardless if the request was successful, or not. You will always receive a complete callback, even for synchronous requests.
ajaxStop () :: Global Event
ajaxStop() method will run if no other requests are pending.
- $( document ajaxStop(function () {
-
- });
In the example hide a loading message after all the Ajax requests have stopped.
- $.ajax() Method basic Configuration settings: var turl = '/Home' + '/SaveEmployeeData';
- var json = "{' empNumber ':'" + 'empId' + "'}";
- $.ajax(
- {
- type: "POST",
- url: turl,
- data: json,
- dataType: 'json',
- async: false,
- contentType: "application/json; charset=utf-8",
- beforeSend: function () {},
- success: function (data) {}
- });
- type: "POST"
“POST” is basically used for sending data along with the request to the server.
It has no restrictions on data length.
POST method never caches data.
Another type call “GET”
GET is basically used for getting (retrieving) some data from the server.
It remains in the browser history and also have length restrictions.
GET method may return cached data.
- url: turl
A string containing the URL to which the request is sent.
var turl = '/Home' + '/SaveEmployeeData';
- data: json
String that is sent to the server with the request.
- var json = "{' empNumber ':'" + 'empId'+ "'}";
Note that in server side method parameter name should be same as json parameter name.
If you are sending an array or an object you need to convert it in to JSON.
The JSON.stringify() method converts a JavaScript value into a JSON string. It is typically used to convert JavaScript arrays or objects to JSON, although it can also be used with simple data types like strings and numbers.
- var empData = [['0', '1', '2', '3', '4', '5'],
- [empNumber, empFirstName, empLastName, empGender, empPhoneNumber, empAddress]];
-
- var json = JSON.stringify(empData);
- dataType: 'json'
A string define the type of data expected back from the server (xml, html, json, or script).
- async: false,
Setting up to true or false indicating whether to perform the request asynchronously.
The default value is true.
async:false will hold the execution of rest code. Once you get response, only then, rest of the code will execute.
- contentType: "application/json; charset=utf-8",
A string containing a MIME content type to set for the request.
The default value is application/x-www-form-urlencoded.
- beforeSend: function () {},
A callback function that is executed before the request is sent.
- success: function (data) {},
A callback function that is executed if the request succeeds.
Inside this function you can do whatever you want because (data) it contains backend results that you looking for.
- cache: false
Whether to use a cached response if available. Defaults to true for all datatypes except "script" and "jsonp".
- timeout: 4000 , //4 second timeout
This is number of milliseconds after which the request will time out on failure.