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();
          $.ajax({
              type: "POST",
              url: webServiceUrl,
              data: "{'name':' Ram John '}",
              contentType: "application/json; charset=utf-8",
              dataType: "json",
              success: SuccessCallBack,
              error: FailureCallBack
          });
      });

      function SuccessCallBack(data) {
          alert(data.d);
      }

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

</script>

 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.
[System.Web.Script.Services.ScriptService]
public class MathService : System.Web.Services.WebService {

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

        [WebMethod]
        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: 6064 | Post Order: 118



Write for us






Hosting Recommendations