Call Web Service using jquery and json

Posted by Akiii under jQuery category on | Points: 40 | Views : 1604
First create a default page. Create and button and a textbox.

Enter Name: <input type="text" id="txtName" />
<asp:Button ID="btnGetMsg" runat="server" Text="Click Me" OnClientClick="DisplayMessageCall();return false;" /><br />
<asp:Label ID="lblOutput" runat="server" Text=""></asp:Label>

Add an asmx file that is the web service file. When you add the asmx file, then it will automatically add app_code folder and in it a .cs file will be added.
Open the .cs file now and add this code :

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService {

public WebService () {

//Uncomment the following line if using designed components

public string HelloWorld(string name)
return "Welcome " + name;


Now add a jquery script reference and add the follwing code to call a webservice file from jquery.

<script type="text/javascript" language="Javascript" src=""></script>
<script type = "text/javascript">
function DisplayMessageCall() {
var pageUrl = '<%=ResolveUrl("~/WebService/WebService.asmx")%>'

type: "POST",
url: pageUrl + "/HelloWorld",
data: "{'name':'" + $("#txtName").val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccessCall,
error: OnErrorCall

function OnSuccessCall(response) {

function OnErrorCall(response) {
alert(response.status + " " + response.statusText);

Now, build the project and run the default page. In that you will see a textbox and button. Write anything in the textbox and click the button. You will see the output !

Thanks and Regards

Comments or Responses

Login to post response