Tums
Tums

Reputation: 505

Calling a web method from jquery ajax

I am trying to call a web method from jquery, but I cannot get it to work. Please note that I have tried to many of the suggestions in other answers, but nothing has worked so far.

When I call the method from the Page_Load, it works correctly. Its only when I call from .ajax() that it fails. I am getting an "internal server error" and when I debug in the browser, I get a "failed to load resource".

For the life of me, I cannot figure out what is wrong. Any help is appreciated.

My ASP code:

        $(document).ready(function () {
        var iipServ = "http://localhost/fcgi-bin/iipsrv.fcgi";
        var imgDir = String($("#<%= hfImageDir.ClientID %>").val());
        var objData = String($("#<%= hfObjectData.ClientID %>").val());
        var docid = $.url(window.location).param('doc');


        $('#diva-viewer').diva({
            iipServerURL: iipServ,
            objectData: objData,
            imageDir: imgDir,
            tileFadeSpeed: 100,
            fixedHeightGrid: true,
            enableAutoTitle: false,
            enableFullscreen: false,
            contained: true,
            enableAutoHeight: true,
            enableAutoWidth: true,
            enableDownload: true,
            zoomLevel: 2
        });

        Events.subscribe("VisiblePageDidChange", function (pagenumber, fn) {

            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "Viewer.aspx/GetTest",
                datatype: "json",       
                data: {docID: JSON.stringify(docid), 
                       pageNumber: JSON.stringify(pagenumber)},
                success: function (response) {

                    alert("YAY!!");
                    alert(response.d);
                    $("#page-data").html(response.d);

                },
                error: function (xhr, status, error) {
                    alert("responseText=" + xhr.responseText + 
                      "\n textStatus=" + status + "\n errorThrown=" + error);
                }                  
            });
        });
    });

And from my code behind page, Viewer.aspx.cs:

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static String GetTest(string docID, string pageNumber)
    {
        String test = "";
        try
        {
            test = "docID = " + docID + " pageNumber = " + pageNumber;
            var ser = new JavaScriptSerializer();
            Show(ser.Serialize(test));

        }
        catch (Exception ex)
        {
            // Log the exception.
            ArchiveViewer.Logic.ExceptionUtility.LogException(ex, 
                 "GetPages in Viewer.aspx.cs");

        }
        return test;
    }

Upvotes: 0

Views: 940

Answers (1)

nick_w
nick_w

Reputation: 14938

There's a couple of problems with your code as it is.

Firstly, you currently pass the data to $.ajax like this:

data: {docID: JSON.stringify(docid),
    pageNumber: JSON.stringify(pagenumber)},

What worked for me was changing it to this:

data: JSON.stringify({docID: docid,
    pageNumber: pagenumber}),

Without that change, jQuery was sending the data to the server as docId=10&pageNumber=20 which was causing JSON deserialization issues on the server-side.

Secondly, you have datatype: "json". It should be dataType: "json", - note the capital T. That said, jQuery will guess what this should be based on what comes back from the server, which in this case is always sending back JSON, but still.

Edit:

In jQuery ajax, the contentType property sets the Content-Type HTTP header on the request, indicating the MIME-type of the request body.

The dataType property sets the Accept header on the request, indicating the MIME-types of the response that are acceptable.

In your case, WebMethods require the Content-Type to be application/json, so setting contentType as you are is correct.

If you want to, you can also set the dataType to be json. It isn't really necessary in this case as jQuery will guess what this should be based on the Content-Type header of the response. As your Web Method is configured to always return JSON, this header should always end up as application/json; charset=utf-8, meaning that jQuery should always make the correct guess.

Upvotes: 2

Related Questions