0

I'm trying to pass a string parameter to a javascript function from the server side which will be posted to an AJAX method. The html is dynamically generated at the server side and I'm calling the javascript function using onclick property. The problem is that it works for a numeric value but I get an internal server error when I pass in a string value.

here's my server side code:

str.Append("<span class=\"button-accept\"><a class=\"btn btn-primary btn-sm\" onclick=\"Request('"+from.ToString()+"')\" href=\"#\"><i class=\"fa fa-check\"></i></a></span>");

Here's my javascript method:

function Request(param) {
        $.ajax({
            type: "POST",
            url: '<%= ResolveUrl("~/myaccount/notifications/Default.aspx/Accept") %>',
            data: "{'param' : "+param+"}",
            contentType: "application/json",
            success: function (msg) {
                msg = msg.hasOwnProperty("d") ? msg.d : msg;
                alert(msg);
            }
        });
    }
    function OnSuccess(response) {
        alert(response.d);
    }

and here's the method that will be called by AJAX:

        [WebMethod]
    public static string Accept(string param)
    {
        return param;
    }

What's the right way to do this?

1 Answer 1

1

The JSON you are passing to the web method is implying that it is an numeric value, add quotes surrounding the param value:

Old

data: "{'param' : "+param+"}",

New

data: "{'param' : '"+param+"'}",

Alternatively ...

If a string is always passed to your Request method, it will be correctly handled using JSON.stringify

data: JSON.stringify({ 'param' : param }),
Sign up to request clarification or add additional context in comments.

Comments

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.