An Introduction to AJAX in ASP.net

The usage of AJAX in ASP.net is fast growing these days as it helps you to create more dynamic, responsive, and better web applications. By using AJAX in ASP.net, the performance of an application is highly increased as the response time is reduced and the traffic between the server and the client is reduced as well. 

You will now learn what AJAX is in ASP.net, its advantages and disadvantages, and how to transfer the data through AJAX in ASP.net.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

What Is AJAX in ASP.net?

AJAX in ASP.net stands for Asynchronous JavaScript and XML. This technique is used to develop rich web applications that are interactive, responsive, and dynamic in nature.

By the method of receiving and sending data to the server in the background, the web pages are updated using AJAX in ASP.net. Without even reloading the web page, you will be able to update the website part by part as well. This update of the website is done asynchronously using AJAX in ASP.net. 

In AJAX, usually, multiple technologies are used together to create these dynamic web pages. Some of these technologies include -

The interactive animation that you see on modern web pages is mainly because of AJAX. In common web pages that do not use AJAX, one needs to reload the entire web page in order to reflect content changes in any parts or all. Now, you are going to discuss the advantages, disadvantages of AJAX in ASP.net and how to transfer data through AJAX in ASP.net.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

Advantages of AJAX in ASP.net

You will explore some advantages of AJAX in ASP.net. Some of these advantages of AJAX in ASP.net are described below -

  • Ajax in ASP.net improves the responsiveness and interactivity of a website.
  • Ajax in ASP.net helps in reducing the traffic between server and client.
  • Ajax in ASP.net reduces the cross-browser issues as it is cross-browser friendly.
  • In Ajax in ASP.net, you can use a single web page or SPA to be able to handle several features and apply multi-purpose applications to it.
  • In Ajax in ASP.net, you can use APIs or Application Programming Interfaces and because these work seamlessly with JavaScript and HTTP methods, it makes it an enormous advantage to building dynamic web applications. 

Disadvantages of AJAX in ASP.net

Let us discuss some disadvantages of AJAX in ASP.net. Some of these disadvantages of AJAX in ASP.net are described below -

  • The size of a data request is largely increased as all these data requests are URL encoded.
  • It highly depends on JavaScript as it is a JavaScript built-in. Therefore, if a user disables JavaScript in the browser, then AJAX stops working.
  • Indexing of an AJAX application cannot be done using Google-like search engines.
  •  Since all the files are downloaded on the client-side in an AJAX application, security is scarce in these applications.
  • Within the AJAX, the server information is completely inaccessible.

How to Transfer the Data Through AJAX?

Now, look at the implementation of transferring data through AJAX in ASP.net. 

There are two ways in which we can transfer data through AJAX -

  1. Server to Client
  2. Client to Server

Now, you will see how to apply and implement both of these ways. 

Consider an entity - Student which contains two fields: ID and Name.

Code Snippet

public class Student

{  

   public int ID { get; set; }  

   public string Name { get; set; }  

1. Server to Client

In ASP.net MVC, we add code in the Controller action. The Controller here is the Student and the action name here is GetStudList which takes a list of students as parameters. 

Code Snippet

public List<Student> GetStudList()  

{  

    var studList = new List<Student>()  

    {  

         new Student { ID=1, Name="Dina"},  

         new Student { ID=2, Name="Chester"}  

    };  

    return studList;  

}

Following this, to get the list of Students, you need to send a request to the Server. To do so-

  1. You need to load the jQuery library. To enable this, you are going to add a jQuery CDN (Content Delivery Network) reference.
  2. To get a list of students from the Server, you have to write and execute a code block and then display it.

Code Snippet

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 

<script type="text/javascript">

    function getStudents() {  

        $.ajax({  

            type: "GET",  

            url: Student/GetStudList',  

            data: {},  

            contentType: "application/json; charset=utf-8",  

            dataType: "json",  

            beforeSend: function(){  

                Show(); // the loader icon is shown here 

            },  

            success: function (response) {  

                // we will loop over the list and then display it

                $.each(response, function (index, stud) {  

                    $('#display').append('<p>Id: ' + stud.ID + '</p>' +  

                                        '<p>Id: ' + stud.Name + '</p>');  

                });  

            },            

            complete: function(){  

                Hide(); // the loader icon is shown here  

            },  

            failure: function (jqXHR, textStatus, errorThrown) {                  

                alert("HTTP Status: " + jqXHR.status + "; Error Text: " + jqXHR.responseText);    //error message is displayed 

            }  

        });  

    }  

</script>

In the above code snippet, “GET” is the method type that gets data as a response parameter in the success properties. This method does the following - loops over the student list collects student data and binds the whole as a div.

In order to display the loader icon when the AJAX request is being sent to the Server and when the AJAX completes, the loader icon is hidden. 

The following code does the job -

<body>  

    <div id="div_Loader" style="padding-left: 400px; top: 500px">  

        <img src="loadingicon.gif" width="50px" height="50px" alt="loader icon" />  

    </div>  

    <div id="display">  

    </div>  

</body> 

2. Client to Server 

To send data from Server to Client using AJAX in ASP.net. Let us see how to do the same from Client to Server using AJAX in ASP.net.

To save the list of students to the database, you have to send these lists of students to the Server. To do so, you need to add the following code to the Controller’s action. The Controller is Student and the action name is SaveStudList that takes in the parameter - list of Students.

Code Snippet

public static bool SaveStudList(List<Student> studList)  

{  

    try  

    {  

        // block of statements to save student list to database

    }  

    catch (Exception ex)  

    {  

        // if logging error arises 

        return false;  

    }  

    return true;  

To send complex objects converted to a list of students to the Server, you have to create an array and then push a JSON object into it. Following this, using the JSON.stringify( ) method, you have to convert this array into JSON string in order to effectively send the data.

<script type="text/javascript"> 

    $(function () {  

        var results = new Array();  

        var stud1 = { "ID": "1", "Name": "Mina" };  

        results.push(stud1);  

        var stud2 = { "ID": "2", "Name": "Shina" };  

        results.push(stud2);       

        var postData = { studList: results };  

        $.ajax({  

            url: 'WebForm1.aspx/SaveStudList',  

            data: JSON.stringify(postData),  

            type: 'POST',  

            contentType: 'application/json',  

            dataType: 'json',  

            beforeSend: function(){  

                Show(); // loader icon shown

            },  

            success: function (result) {  

                alert(result);  

            },  

            complete: function(){  

                Hide(); // loader icon  is hidden

            },  

            failure: function (jqXHR, textStatus, errorThrown) {                  

                alert("Status: " + jqXHR.status + "; Error: " + jqXHR.responseText);

 //error message displayed            

       }  

        });  

    });  

    $(document).ready(function () {  

        $("#div_Loader").hide();  

    });  

    function Show() {  

        $('#div_Loader').show();  

    }   

    function Hide() {  

        $('#div_Loader').hide();  

    }  

</script> 

Through this, using $.Ajax, you can implement AJAX in jQuery.

Conclusion

AJAX is used to create dynamic web pages that do not require page reloading when any part of the whole web page content or the whole web page content is changed. The server data exchange is asynchronous in nature and AJAX in ASP.net uses multiple technologies like XSLT, XHTML, CSS, JavaScript, etc.

To master and learn more about AJAX in ASP.net and all its related technologies properly and well versed to get into full-stack development, one might consider referring and learning in-depth from various resources, study materials, and course books.

If you are interested in understanding and acquiring knowledge on AJAX in ASP.net and all its related technologies in order to become a full-stack web and desktop application developer, Simplilearn offers an exclusive Full Stack Developer - MERN Stack to master both backend and frontend with tools, like SpringBoot, AngularMVC, JSPs, and Hibernate to start your career as a full-stack developer. 

If you are not up to enrolling yourself into the full certification course yet, Simplilearn also offers free online skill-up courses in several domains, from data science and business analytics to software development, AI, and machine learning. Become a full-stack web developer today!

If you have any queries leave them in the comments section of this article and our experts will get back to you on the same, ASAP!

About the Author

Ravikiran A SRavikiran A S

Ravikiran A S works with Simplilearn as a Research Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.