Search code examples
c#asp.netjquerywebmethod

returning complete page HTML instead of string output in JSON response


I am trying to achieve a simplest task through ajax using web method . My web method as follow

[WebMethod]
    public static string GetDate()
    {
        return string.Format("says {0}", DateTime.Now.ToString("r"));
    }

and ajax code as follow

 $(document).ready(function() {
            $("#Result").click(function() {
                alert('Result Clicked');

                $.ajax(
               {
                   type: "POST",
                   url: "test1.aspx/GetDate",
                   data : "{}",
                   contentType: "application/json",
                   dataType: "json text",
                   success: function(rsp) {

                       alert('success');
                       alert(rsp);
                       alert(rsp.d);

                       $('#Result').append(rsp.d);


                   },
                   error: function(rsp) {
                       alert(rsp.status + " " + rsp.statusText + "</br>" + rsp.responseText);
                       console.log(rsp);
                       console.log(rsp.responseText);

                   }
               });
            });

        });

but status says OK and 200 status code, but instead of simple string in rsp.d its shows complete HTML of that page self.


Solution

  • You Can Try this Code May be it is Help Full.

    $("#Result").click(function () {
                    alert('Result Clicked');
                    $.ajax(
                        {
                       type: "POST",
                       url: "Default.aspx/GetDate",
                       contentType: "application/json; charset=utf-8",
                       dataType: "json",
                       success: function (rsp) {
                           alert('success');
                           alert(rsp);
                           alert(rsp.d);
                           $('#Result').append(rsp.d);
                       },
                       error: function (rsp) {
                           alert(rsp.status + " " + rsp.statusText + "</br>" + rsp.responseText);
                       }
                   });
                });