This is a mirror of official site: http://jasper-net.blogspot.com/

Calling an asp.net web service from jQuery

| Monday, August 30, 2010
As I have post it in earlier post that jQuery is one of most popular JavaScript library in the world amongst web developers Lets take a example calling ASP.NET web service with jQuery . You will see at the end of the example that how easy it is to call a web service from the jQuery.

Let’s create a simple Hello World web service. Go to your project right click->Add –> New Item and select web service and add a web service like following.

[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 PrintMessage()
 {
     return "Hello World..This is from webservice";
 }
}

...

Now let’s add some JavaScript code to call web service methods like following.

<script language="javascript" type="text/javascript">
         function CallWebServiceFromJquery() {
       
         $.ajax({
             type: "POST",
             url: "HelloWorld.asmx/PrintMessage",
             data: "{}",
             contentType: "application/json; charset=utf-8",
             dataType: "json",
             success: OnSuccess,
             error: OnError
                         });
         
     }

     function OnSuccess(data, status)
     {
        alert(data.d);
     }

     function OnError(request, status, error)
     {
         alert(request.statusText);
     }
</script>

Read more: DOTNETJAPS ALL ABOUT .NET

Posted via email from .NET Info

0 comments: