Monday, April 13, 2015

Http handler call from jquery

Generally webmethod call from jquery is very simple and it can be done via following code:
 $.ajax({ type: "POST",
                    url: "Page.aspx/GetDates",
                    data: '{para1:"' + para1Value + '",para2: "' + para2Value + '"}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        alert(response.d);
                    },
                    failure: function (response) {
                        alert(response);
                    }
                });



But same above code will not work in case of httphanlder call. I have found few reasons behind this:
In httphandler we are getting data in form of Request.Params(eg. Request.Param["para1"]) which only supports url encoded data. So json posted data will not work in above code.
So following code can be used instead of above:

$.ajax({
                  type: "POST",
                  url: "Handler.ashx",
                  data: { fName: firstName },
                 // dataType: "json",

                   beforeSend: function (xhr, settings) {
                      //$("[id$=processing]").dialog();
                      alert('st');
                  },
                  success: function (msg) {
                      alert(msg);
                      alert(msg.d);
                  },
                  error: function () {
                      alert("Error");
                  }

              });


See difference no content type and no data type. Thats it!