0

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;
    }
5
  • @KhanhTO Wouldn't he need the contentType in there? And dataType only affects what comes back from the server - the error in this case happens earlier - though I do acknowledge that it should be changed all the same. Commented Jan 19, 2014 at 8:58
  • Question re: the contentType? I will be passing JSON data back (this is not my real function). When should I use 'application/x-www-form-urlencoded; charset=UTF-8'? Commented Jan 19, 2014 at 9:35
  • @KhanhTO Looking at this link: weblogs.asp.net/scottgu/archive/2007/04/04/… it seems as though WebMethods require the content type to be set to application/json. Commented Jan 19, 2014 at 9:41
  • @nick_w: thanks, I was not sure. That why I posted as a comment Commented Jan 19, 2014 at 9:43
  • @Tums See the edit to me answer. Commented Jan 19, 2014 at 9:53

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I was indeed passing the data incorrectly. I tried so many variants of that line from looking at many examples, but I must have missed that one (or typed it incorrectly). Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.