jQuery > How to Solution

Consume web services from jQuery in jQuery

How to consume web services from jQuery?

To consume web services from jQuery, we can use $.ajax method and pass conetntType as “application/json” and dataType as “json”.

jQuery code

 <script language="javascript" type="text/javascript">

      $("#btnAjax").click(function () {
          var webServiceUrl = "../MathService.asmx/GetFullName";
          var name = $("#txtBoxName").val();
              type: "POST",
              url: webServiceUrl,
              data: "{'name':' Ram John '}",
              contentType: "application/json; charset=utf-8",
              dataType: "json",
              success: SuccessCallBack,
              error: FailureCallBack

      function SuccessCallBack(data) {

      function FailureCallBack(data) {
          alert(data.staus + " : " + data.statusText);


 Web Service Code

/// <summary>
/// Summary description for MathService
/// </summary>
[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.
public class MathService : System.Web.Services.WebService {

    public MathService () {
        //Uncomment the following line if using designed components

        public string GetFullName(string name)
            return "[Webservice response]\n\nYou have entered : " + name ;

Notice the MathService class attribute, System.Web.Script.Services.ScriptServices is the mandatory to keep for any web services to be consumed through client side script like JavaScript.

 Views: 1112 | Post Order: 118

Write for us