Saturday, January 21, 2012

JQuery Ajax Examples by calling asp.net webservice

In this article, i will be calling asp.net web service using jQuery Ajax.

With JQuery Ajax you can do

  • Make a database call and perform CRUD operation (Create, Read, Update and Delete) without page postback
  • If you have used Ajax Control Toolkit in past then you will be able to do almost all such operations and lot more by using jQuery Ajax and JQuery UI.

If you are new to jQuery and don't know anything about it, I will recommend you to first read following article before reading any further.

OK, so lets start the real fun

Since it is our first example, lets keep it simple and display "Hello World". Check out Live Demo

Step 1: Create Asp.net Web Application


Step 2: Open Site.Master and include jQuery Reference by adding below line just before </head> tag.
<!--Include JQuery File-->
<script type="text/javascript" language="Javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>




Step 3: Open "Default.aspx" and add following code
I have added here h2 title tag, asp.net button and label.  Please note, that i have declared OnClientClick, I will be calling javascript function, which will internally make jQuery Ajax call to asp.net web service.
<h2>Example 1: Call Webservice using JQuery AJax (Without Input)</h2>


<asp:Button ID="btnGetMsg" runat="server" Text="Click Me" OnClientClick="DisplayMessageCall();return false;" /><br />


<asp:Label ID="lblOutput" runat="server" Text=""></asp:Label>


Step 4: Add new folder to solution named "WebService"


Step 5: Right click on "WebService" folder and click add new item, to add new web service.


Step 6: Add code to display message inside "HelloWorld.asmx.cs" file
///
/// Summary description for HelloWorld
///
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class HelloWorld : System.Web.Services.WebService
{
    [WebMethod]
    public string DisplayMessage()
    {
        return "Hello World using jQuery Ajax";
    }
}
Important Note:  Please UnComment line
[System.Web.Script.Services.ScriptService]
In order to allow this Web Service to be called from script, using ASP.NET AJAX



Step 7:  Open "Default.aspx" and Write jQuery function to make webservice call to display "Hello World" message.
<script type = "text/javascript">
    function DisplayMessageCall() {


        var pageUrl = '<%=ResolveUrl("~/WebService/HelloWorld.asmx")%>'


        $.ajax({
            type: "POST",
            url: pageUrl + "/DisplayMessage",
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccessCall,
            error: OnErrorCall
        });


    }


    function OnSuccessCall(response) {
        $('#<%=lblOutput.ClientID%>').html(response.d);
    }


    function OnErrorCall(response) {
        alert(response.status + " " + response.statusText);
    }
</script>

Understanding jQuery Ajax call parameter
  • type: Can be POST or GET.
  • url: Path of webservice file (Example here: path of HelloWorld.asmx file) In the above code you can find that i have declare path of webservice in pageurl variable.  Since we are going to call "DisplayMessage" method name inside webservice we have write pageUrl + "/DisplayMessage"  (i.e. Webservice Path + Method Name)
  • data: In this example the data will remain empty, as we are only calling a method which return a simple string and don’t accept any parameter. If the method has some parameters then we will pass the parameters. I will explain on passing parameters in my coming posts.
  • contentType: Should remain the same.
  • datatype: Should remain as it is.
  • success: Here I have called the OnSuccessCall when the call is complete successfully. If you check the OnSuccessCall method you will see that I have set the returned result from the web service to the label. In the OnSuccessCall method body you see ‘data.d’. The ‘d’ here is the short form of data.
  • Error: Same as I have done with OnSuccessCall. If any error occurred while retrieving the data then the OnErrorCall method is invoked.
Now, run the web application and hit button to see message.

Check out Live Demo of Calling Webservice using JQuery Ajax Example

Note: Please remember, JQuery is Javascript library so you will NOT be able to retrieve large amount of data or do heavy database operations.  Example: If you want to load 7000 Records from database then JQuery Ajax is not good approach.  To best of my knowledge you will never run into such situation except loading cascading dropdown, incase you run in any such situation than you should rethink your approach.

5 comments:

Unknown said...

thanks you very.
this is very nice post.

Unknown said...

excellent article for beginners..

Unknown said...

Thanks for a very nice post, which was well written, clearly explained and an excellent resource for developers new to JQuery.

Nishant Chandwani said...

Thankyou but i have a problem in PageUrl it give a error server is not found

Anonymous said...

I truly like to reading your post. Thank you so much for taking the time to share such a nice information.
web grid

Most Recent Post

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape