How to use Jquery Ajax calls ?

Reading Time: 2 minutes

What is AJAX?

AJAX stands for Asynchronous JavaScript and XML, which, simply, is a way of transferring data between the server and client without reloading the entire page. In this article, I will show you how to implement Jquery Ajax in your website in two ways. How to call an API and how to call a Web method.

Simple example:

Suppose you are filling data in a table, and you want the table to load asynchronously in the background and show a loading indicator.

Without ajax or asynchronous calls, you will have to load the table in the page events which may cause bad experience for the user, while with using asynchronous calls like Ajax in our case we will make the whole page load and the table will load alone in the background with loading sign which will make improve user experience.

ajax h-educate

source: www.w3schools.com

 

In this article, I will not talk about ajax.Net control, But I wanna explain the concept of calling server-side methods or WebApi using jquery ajax calls for beginners.

HTTP Request: GET vs. POST

Two commonly used methods for a request-response between a client and server are GET and POST.

  • GET – Requests data from a server.
  • POST – Submits data to the server.

 

Sample example ajax code to call Web API:

 

$.ajax({
type:"GET",
url:"https://pathtoYourApi",
success: function(data) {
$('.text').text(JSON.stringify(data));
},
dataType: 'jsonp',
});

 

Sample code to call a web method (general form):

 

<script type="text/javascript">   
    //Called this method on any button click  event for Testing
    function MyFunction(Param1, Param2) {                                               
    $.ajax({
        type: "POST",
        url: "MyPage.aspx/MyMethod",
        data: "{ Param1: '" + Param1+ "',Param2: '" + Param2 + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: "true",
        cache: "false",
        success: function (msg) {
            // On success                 
        },
        Error: function (x, e) {
            // On Error
        }
    });
}  
</script>

 

On the server side (web method):

 

[WebMethod]
public static void MyMethod(string Param1, string Param2)
{ 
     try
     {
        //Do here server event  
     }
     catch (Exception)
     { 
       throw;
     }  
}

 

Leave a Comment

Your email address will not be published. Required fields are marked *