In jQuery we can perform an asynchronous HTTP (Ajax) request. In this post we will see simple example of how jquery Ajax call to WCF service works. We can call wcf service using jquery ajax and json.
var dto = { message: $("#messageinput").val() };
$.ajax({
type: 'GET',
url: '',
data: dto,
contentType: "application/json; charset=utf-8"
})
.success(function (response) {
alert(response.d);
})
.error(function (response) {
alert("ERROR"+response.d);
});
Here in above code snippet we have set various parameters for jquery ajax call like: type: 'GET' - means request is of type GET and not POST
url: '', here we have mentioned the url of wcf service, where Service1.svc is wcf service name, get-json is address set in the web.config wcf service
data: dto is the parameter data that we need to pass to wcf service method.
Example jquery ajax call to wcf service
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<title>Jquery ajax json call to wcf service</title>
<script type="text/javascript">
$(document).ready(function () {
$("#btnClick").click(function () {
var dto = { message: $("#messageinput").val() };
$.ajax({
type: 'GET',
url: '<%= ResolveUrl("~/Service1.svc/get-json/GetMessage") %>',
data: dto,
contentType: "application/json; charset=utf-8"
})
.success(function (response) {
alert(response.d);
})
.error(function (response) {
alert("ERROR"+response.d);
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="text" id="messageinput" />
<asp:Button ID="btnClick" runat="server" Text="Button" />
</div>
</form>
</body>
</html>
In above example we can type some message in textbox and pass message to wcf service using jquery ajax call and get it in respose back.
Note: To run above example we need to create wcf service and configure wcf service endpoint in web.config file properly
0 Comments :
Post a Comment