Search code examples
asp.netajaxwebmethod

AJAX - "Success" action is not invoked when specifying contentType and dataType


I run into a little bit of a problem executing `AJAX request.

When specifying contentType and dataType, success section is not executing. However, when omitting that, it is executing, but is showing the entire content of generated html page.

Here is my AJAX call:

$.ajax({
    type: "POST",
    url: "Default.aspx/GeneratePdfs",
    data: '{frequency: "' + $('#ddlFrequency option:selected').text() + '" }',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        $('#rptDisplay').text(data);
        alert("1");
    },
    failure: function () {
        //                $('#rptDisplay').text("Error");
        alert("2");
    }
});

This is code behind:

[System.Web.Services.WebMethod]
public static void GeneratePdfs(string frequency)
{
    string test = frequency;
    HttpResponse response = HttpContext.Current.Response;
    response.Write(test);
}

This is the fragment of html page:

<div id="rptDisplay" class="well" runat="server" clientidmode="Static">

</div>

I need to display data returned from Web Method in my div section.

What am I doing wrong?


Solution

  • Hope this will help you:

    contentType :When sending data to the server.

    dataType: The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response .

    Please find the code:

        [System.Web.Services.WebMethod]
        public static string GeneratePdfs(string frequency)
        {
            string test = "frequency";//Hard Code value
            HttpResponse response = HttpContext.Current.Response;
            return test;
        }
    
         Design:
          <asp:Content runat="server" ID="BodyContent"   ContentPlaceHolderID="MainContent">
          <div id="rptDisplay" class="well" runat="server" clientidmode="Static">
    
          </div>
        <script src="Scripts/jquery-1.7.1.min.js"></script>
        <script src="Scripts/jquery-ui-1.8.20.min.js"></script>
        <script type="text/javascript">
        $.ajax({
            type: "POST",
            url: "Default.aspx/GeneratePdfs",
            data: '{frequency: "' + $('#ddlFrequency option:selected').text() + '" }',
            contentType: "application/json;charset=utf-8",
           // dataType: "text/Json",
            success: function (data) {
                debugger;
                if (data.d!="") {
                    $('#rptDisplay').text(data.d);
                }
                alert("1");
            },
            failure: function () {
                //                $('#rptDisplay').text("Error");
                alert("2");
            }
        });
    </script>