How To Call ASP.NET Web Service Using jQuery Ajax

In this article, I am going to share how to call ASP.NET Web Service method using jQuery AJAX.

Step 1

Create an empty ASP.NET Web Application.

ASP.NET Web Service

Step 2

Right-click on the Project to add a service to your application (Add>New Item) and click on "New Item" option as shown in the below picture.

ASP.NET Web Service

Step 3

Select Web Service item (ASMX) and give the name as you want. I have left the default name and clicked on Add option. In my case, the name of the service is WebService1.asmx.

ASP.NET Web Service

Step 4

Once you have added the service, you will get the following code.

ASP.NET Web Service

Step 5

Let us focus on the comment. The given comment is “To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line”. It means - you will have to uncomment the below (// [System.Web.Script.Services.ScriptService]) code to be called from jQuery AJAX.

Step 6

I have changed “HelloWorld” function parameter and passed one parameter named as myUserName and data type as a string. The function is returning “HelloWorld” plus input parameter.

ASP.NET Web Service

Step 7

Now, it is time to write jQuery AJAX code to call “HelloWorld” Service Method.

In order to write the code, you will have to add one webpage where you can write jQuery AJAX code. I have added one webpage to my application as you can see in the below image.

ASP.NET Web Service

Step 8

Now, add jQuery script to the .aspx page(Script is given below) as you can see in the given figure.

  1. <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>  

ASP.NET Web Service

Step 9

Write the following code inside the head section of .aspx page  to call HelloWorld Method of WebService.

  1. <script type="text/javascript">  
  2.     $(document).ready(function() {  
  3.         $.ajax({  
  4.             type: "POST",  
  5.             url: "WebService1.asmx/HelloWorld",  
  6.             data: "{'myUserName':'MyUserNameIsRaj'}",  
  7.             contentType: "application/json",  
  8.             datatype: "json",  
  9.             success: function(responseFromServer) {  
  10.                 alert(responseFromServer.d)  
  11.             }  
  12.         });  
  13.     });  
  14. </script>  

Step 10

Now, see the final output.

ASP.NET Web Service

Remarks

You can download this working application from the below link.

Ebook Download
View all
Learn
View all