jQuery AJAX call to an ASP.NET WebMethod

I have the following jQuery AJAX request:

function sendUpdate(urlToSend) {
    var code = AccessCode; 
    var url = urlToSend;
    var options = { error: function(msg) { alert(msg.d); },
                    type: "POST", url: "webmethods.aspx/UpdatePage",
                    data: "{ accessCode: " + code + ", newURL: '" + url + "' }",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    async: true, 
                    success: function(response) { var results = response.d; } }; 
    $.ajax(options);
}

And the corresponding ASP.NET WebMethod:

[WebMethod]
public static bool UpdatePage(string accessCode, string newURL)
{
    bool result = true;
    try
    {
        HttpContext.Current.Cache[accessCode + "l"] = newURL;
    }
    catch
    {
        result = false;
    }

    return result;
}

That all used to work correctly with "async:false", however I have to get rid of it as it freezes the browser until the response is received. Now the AJAX request above returns "undefined".

Could anybody tell me why it happens and where the problem is?

Thanks.


You should really make sure to properly encode this JSON. JSON.stringify is the most reliable method:

data: JSON.stringify({ accessCode: code, newURL: url })

This ensures that even if the code and url variables contain some dangerous characters that will break your string concatenations in the resulting JSON at the end everything will be properly encoded. The JSON.stringify method is natievly built into modern browsers but if you need to support legacy you could include json2.js.

Also because you code is no longer blocking you should make sure that if you call this sendUpdate from some button click or form submit you cancel the default action by returning false.


My way works correctly:

[System.Web.Services.WebMethod()] 

        public static string getHello(string str)
        {
            //do some things with str   
            return str;
        }

In file .js, I define this function to call webmethod in file .cs:

function CallServerFunction(StrPriUrl, ObjPriData, CallBackFunction) {

    $.ajax({
        type: "post",
        url: StrPriUrl,
        contentType: "application/json; charset=utf-8",
        data: ObjPriData,
        dataType: "json",
        success: function (result) {
            if (CallBackFunction != null && typeof CallBackFunction != 'undefined') {
                CallBackFunction(result);
            }

        },
        error: function (result) {
            alert('error occured');
            alert(result.responseText);
            window.location.href = "FrmError.aspx?Exception=" + result.responseText;
        },
        async: true
    });
}

Then, call to use (call in file.js):

 var text = $("#textbox_send").val();

    var myresult;
    CallServerFunction("Default.aspx/getHello", JSON.stringify({ str: text }), function (myresult) {
        if (text != "")
            $('#' + id).append('<p>' + $("#account_user").text() + ': ' + myresult.d + '</p>');
    });