Atlim
Atlim

Reputation: 91

AJAX call returns page HTML / doesn't hit Page Method is ASP.Net (no MVC or Json)

I am updating a tool for my current company that provides basic product layout documents depending on choices picked. Recently it appears a bot of some sort has been hitting the toolbox periodically, and after some discussion with the company we built the toolbox for we have decided to add the ReCaptcha tool to the page.

The way the toolbox was setup is ASP.net without the use of Json or MVC (the toolbox is a fair few years old, built long before I joined the team). Adding the ReCaptcha tool was not an issue, I did it without a plugin using a window.onload function and using their instructions. This was all done on the options.aspx page, the code for the ReCaptcha call is in the options.aspx.cs page.

To reach this code I am attempting to do an AJAX call where the form would normally be submitted.

The issue: Each AJAX call returns the HTML of the page, and the Page Method (VerifyReCaptcha) does not trigger when I have a break point in it. I need it to call the method which will do all of the listing, then simply pass back a string that simply says if it was a success or not. It doesn't seem to matter what dataType or contentType I enter (if any), or if I run it as POST or GET.

Here is the code of the button that calls the function for the ajax call.

    <input type="button" id="DownloadLayoutButton" value="Download Layout" class="navigationButton" style="width: 200px; height: 24px;" />

Here is the function that is called.

    $("#DownloadLayoutButton").click(function () {
        $.ajax(
        {
            url: "options.aspx/VerifyReCaptcha",
            dataType: "text",
            data: {
                challenge: Recaptcha.get_challenge(),
                response: Recaptcha.get_response()
            },
            type: "POST",
            success: function (result) {
                if (result == "Success") {
                    alert("Success!");
                else
                    alert("ReCaptcha entry was incorrect!");
            },
            error: function (request, status, error) {
                alert("Error!");
            }
        });
    });

This code never seems to hit the VerifyReCaptcha() method that is on the options.aspx.cs page, the method is as follows. As stated I have tested and confirmed that this function works on its own. Previously I had it returning a boolean value but since ajax can't work with booleans, I changed it to return "Success" or "Failure" depending on the result.

    [WebMethod]
    public static string VerifyReCaptcha(string challenge, string response)
    {
        try
        {
            string PRIVATE_KEY = "MY_KEY_HERE";
            string remoteip = HttpContext.Current.Request.UserHostAddress;

            WebRequest request = WebRequest.Create("http://www.google.com/recaptcha/api/verify");

            byte[] dataBytes = System.Text.Encoding.UTF8.GetBytes(String.Format("privatekey={0}&remoteip={1}&challenge={2}&response={3}", PRIVATE_KEY, remoteip, challenge, response));

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = dataBytes.Length;

            request.GetRequestStream().Write(dataBytes, 0, dataBytes.Length);

            String resultString = String.Empty;
            String errorString = String.Empty;

            using (StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream()))
            {
                resultString = sr.ReadLine();
                errorString = sr.ReadLine();
            }

            Boolean b;
            b = Boolean.TryParse(resultString, out b) && b;

            if (b)
                return "Success";
            else
                return "Failure";
        }
        catch (Exception)
        {
            return "Failure";
        }
    }

The aspx page is using the following sources.

    <script type="text/javascript" src="JS/jquery-1.3.2.min.js"></script>
    <script type="text/javascript" src="JS/jquery-validate/jquery.validate.js"></script>
    <script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>

Upvotes: 2

Views: 3103

Answers (2)

Peter Hahndorf
Peter Hahndorf

Reputation: 11212

As I understand it, asp.net WebMethods expect posted data in JSON. In your JavaScript jQuery Ajax call use dataType: "json" rather than dataType: "text".

I also add contentType: "application/json; charset=utf-8" as another option.

The WebMethod is not called if the doesn't find the correctly formatted data it expects.

Upvotes: 0

Karl Anderson
Karl Anderson

Reputation: 34846

Your ASP.NET AJAX Page Method needs to be static.

You have:

public virtual string VerifyReCaptcha()

It needs to be:

public static virtual string VerifyReCaptcha()

Note: Read Why do ASP.NET AJAX page methods have to be static? for more information.

Upvotes: 2

Related Questions