Call Web Method From jQuery

It is quite a common situation to call a server side method from client side using jQuery. In this article we will learn how we can call a simple method in the code behind file from jQuery. 
 
To start with we create a new ASP.NET project and add a web page named WebMethodCall.aspx. Next, we add a textbox in the html of this page. Add reference to the jQuery from online. We will get data from server using the click of this button and display it in alert box. So our markup will look like the following:  
  1. <head runat="server">    
  2.     <title></title>    
  3.     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>    
  4. </head>    
  5. <body>    
  6.     <form id="form1" runat="server">    
  7.         <div>     
  8.             <input type="button" title="Click to call server method" value="Get data  from server" />     
  9.         </div>    
  10.     </form>    
  11. </body>    
Next, add the following script to call the server method from client side.
  1. <script type="text/javascript">  
  2.               function GetData() {  
  3.                   $.ajax({  
  4.                       type: "POST",  
  5.                       url: "WebMethodCall.aspx/GetData",  
  6.                       data: '',  
  7.                       contentType: "application/json; charset=utf-8",  
  8.                       dataType: "json",  
  9.                       success: function (response) {  
  10.                           alert(response.d);  
  11.                       },  
  12.                   });  
  13.               }  
  14.           </script>  
Next, we add the server side method on the WebMethodCall.aspx.cs, which will return a string of the current date time. One important point to note is that we need to mark our method with the [WebMethod] attribute. So our method will look like the following: 
  1. [System.Web.Services.WebMethod]  
  2. public static string GetData()  
  3. {  
  4.     return DateTime.Now.ToString();  
  5. }  
 That's it. We are done. Run the application and see the results:
 
 
 
Happy coding...!!!
 
Read more articles on jQuery:


Similar Articles