Calling a Webmethod Using Jquery Ajax

Introduction

This tip explains how to call a web method using JQuery.There are so many ways we can do this requirement. Here I am explaining one.

Steps

We need to include:
[js]
<script src="Script/jquery-1.9.1.min.js" type="text/javascript"></script>
[/js]

After that, create an Ajax jQuery function like this:
[js]
function checkUserNameAvail() {
var userid = $("#reguser").val();
jQuery.ajax({
type: "POST",
url: "Login.aspx/checkUserNameAvail", //It calls our web method
contentType: "application/json; charset=utf-8",
data: "{‘iuser’:’" + userid + "’}",
dataType: "xml",
success: function (msg) {
$(msg).find("Table").each(function () {
var username = $(this).find(‘UserName’).text();
if (username != ”) {
//window.location.replace(‘/iCalendar.aspx’);
alert(‘This username already taken..’);
$("#reguser").val(”);
$("#reguser").focus();
}
else {
}
});
},
error: function (d) {
}
});
}
[/js]

Make sure that you have included the js file to the aspx page.

Create a web method in your aspx.cs file like the following:
[csharp]
[WebMethod(enableSession: true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public static string checkUserNameAvail(string iuser)
{
try
{
//This is where i am returning my data from DB

iCalendarClass iC = new iCalendarClass();
DataSet ds = iC.checkUserNameAvail(iuser);
return (ds.GetXml());
}
catch
{
return null;
}
}
[/csharp]
Make sure that your function returns XML.

That’s all. Have a happy coding 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

Serverless 360