Using JSON, AJAX, jQuery With ASP.NET MVC 4 Application - Part 1

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)
    1.   var jsonObj = {marks: 92}
  • A string (in double quotes)
    1. var jsonObj = { firstName: 'kamal'}  
  • A Boolean (true or false)
    1. var jsonObj = { isHoliday : true }  
  • An array (in square brackets)
    1. var jsonObj = '{ "employees":[  
    2.    {"firstName":"kamal""age":"21"},   
    3.    {"firstName":"Aruna""age":"25"},   
    4.    {"firstName":"Peter","age":"18"} }';  
    5. ]  
  • An object (in curly braces)
    1. 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:
    1. 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].

controller

Google Maps, Gmail, YouTube and Facebook update the part of the web page without having to reload the entire page.

How AJAX Works

AJAX Works

Ajax Events

There are two types of events:

  1. Local Event

    These are events that you can subscribe within the Ajax request object.

  2. 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. 

  1. $( document ).ajaxStart(function() {  
  2.    //do my global thing here  
  3. });  
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.
  1. $( document ).ajaxSend(function() {  
  2.    //do my global thing here  
  3. });  
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.
  1. $.ajaxSuccess(function(){  
  2.    //do my global thing here  
  3. });  
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.
  1. function getErrorMessage(jqXHR, exception)  
  2. {  
  3.     var msg = '';  
  4.     if (jqXHR.status === 0)  
  5.     {  
  6.         msg = 'Not connect.\n Verify Network.';  
  7.     }  
  8.     else if (jqXHR.status == 404)  
  9.     {  
  10.         msg = 'Requested page not found. [404]';  
  11.     }  
  12.     else if (jqXHR.status == 500)  
  13.     {  
  14.         msg = 'Internal Server Error [500].';  
  15.     }  
  16.     else if (exception === 'parsererror')  
  17.     {  
  18.         msg = 'Requested JSON parse failed.';  
  19.     }  
  20.     else if (exception === 'timeout')  
  21.     {  
  22.         msg = 'Time out error.';  
  23.     }  
  24.     else if (exception === 'abort')  
  25.     {  
  26.         msg = 'Ajax request aborted.';  
  27.     }  
  28.     else  
  29.     {  
  30.         msg = 'Uncaught Error.\n' + jqXHR.responseText;  
  31.     }  
  32.     $('#post').html(msg);  
  33. }  
Instead of using this you can also view this in your own browser console, by using console.log inside the error function like:
  1. error: function (jqXHR, exception) {  
  2.    console.log(jqXHR);  
  3. }  
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.
  1. $(document).ajaxComplete(function() {  
  2.    //your code here  
  3. });  
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.
  1. $( document ajaxStop(function () {  
  2.    //your code here  
  3. });  
In the example hide a loading message after all the Ajax requests have stopped.
  1. $.ajax() Method basic Configuration settings: var turl = '/Home' + '/SaveEmployeeData';  
  2. var json = "{' empNumber ':'" + 'empId' + "'}";  
  3. $.ajax(  
  4. {  
  5.     type: "POST",  
  6.     url: turl,  
  7.     data: json,  
  8.     dataType: 'json',  
  9.     async: false,  
  10.     contentType: "application/json; charset=utf-8",  
  11.     beforeSend: function () {},  
  12.     success: function (data) {}  
  13. });   
  • 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.
    1. 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.
    1. var empData = [['0''1''2''3''4''5'],  
    2. [empNumber, empFirstName, empLastName, empGender, empPhoneNumber, empAddress]];  
    3.   
    4. 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.


Similar Articles