Below are the steps to call web service from html page using jquery
1. Create a Web Service with marked as ScriptService
[System.Web.Script.Services.ScriptService]
public class TestService : System.Web.Services.WebService
{
This will allow the Web Service to be called from script, using ASP.NET AJAX.
2. Create a method with marked as WebMethod and ScriptMethod for enabling client access.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string CreateAccount(RequestData objRequestData)
{
Since I am using the JSON as the data type I am marking the Response format as JSON.
Web Service Example
[System.Web.Script.Services.ScriptService]
public class TestService : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string CreateAccount(RequestData objRequestData)
{
return objRequestData.Name;
}
}
Call Web Service from HTML Page
To call web service from HTML page $.ajax is used.The data send should be as object “objRequestData “. This is very important otherwise it wont work.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="jquery-1.7.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
});
var GetJson = function () {
var requestdata = {};
requestdata.Name = "Amar Prakash";
var pdata = { "objRequestData": requestdata };
$.ajax({
type: "POST",
data: JSON.stringify(pdata),
url: "http://localhost:54016/TestService.asmx/CreateAccount",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.d);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
</script>
</head>
<body>
<br />
<input type="button" id="jsonButton" onclick="GetJson()" value="Bind JSON" />
<br />
<br />
<div id="jsonData">
</div>
</body>
</html>
Hai,
I tried your above code it is giving error in web service creation
Error : The type or namespace name ‘RequestData’ could not be found (are you missing a using directive or an assembly reference?)
Please guide me which reference do i need to give here.