How to call the webservice using Ajax on client side?


Hi
I hope that you are knowing the basic concept of web service.
There are so many method to call the web service.
1.Using Ajax (script manager control) and JavaScript
2.using Jquery.
3.Using C# code.

Here i m going to show you using script manager and Javascript.
Step1. Create the simple webservice like this, and UnComment this line
[System.Web.Script.Services.ScriptService]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

///
/// Summary description for WebService
///
[WebService(Namespace = “http://tempuri.org/”)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 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 WebService : System.Web.Services.WebService {

public WebService ()

{

//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod]
public string HelloWorld() {
return “Hello World”;
}

}

Step2: Write the Javascript code in default page like this

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default2.aspx.cs” Inherits=”Default2″ %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head runat=”server”>
<title></title>
<script language=”javascript” type=”text/javascript”>
function onClick()

{

WebService.HelloWorld(OnComplete, OnTimeOut, onerror);

return true;
}
function OnComplete(args) {
document.getElementById(‘Label1’).innerHTML = args;
}
function OnTimeOut(args) {
alert(“Service call timed out.”);
}

function OnError(args)

{
alert(“Error calling service method.”);
}
</script>
</head>

<body>

<form id=”form1″ runat=”server”>
<div>
<asp:ScriptManager ID=”ScriptManager1″ runat=”server” >
<Services>
<asp:ServiceReference Path=”WebService.asmx” />
</Services>
</asp:ScriptManager>
<input id=”Button1″ type=”button”
value=”button” onclick=”return onClick();” />
<br />
<br />
<label id=”Label1″ style=”width: 318px”></label>

</div>
</form>
</body>
</html>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: