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.
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.
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.
Step 4
Once you have added the service, you will get the following code.
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.
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.
Step 8
Now, add jQuery script to the .aspx page(Script is given below) as you can see in the given figure.
- <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
Step 9
Write the following code inside the head section of .aspx page to call HelloWorld Method of WebService.
- <script type="text/javascript">
- $(document).ready(function() {
- $.ajax({
- type: "POST",
- url: "WebService1.asmx/HelloWorld",
- data: "{'myUserName':'MyUserNameIsRaj'}",
- contentType: "application/json",
- datatype: "json",
- success: function(responseFromServer) {
- alert(responseFromServer.d)
- }
- });
- });
- </script>
Step 10
Now, see the final output.
Remarks
You can download this working application from the below link.