jpavlov
jpavlov

Reputation: 2261

Passing multiple parameters with Ajax

I have a function in my .aspx page where I collect the first name and last name from the user and would like it to pass back to the server side code(c#). Ajax is being used and runs fine when one parameter is passed, although when a second parameter is passed I receive an error : can someone shed a little light, thanks

ERROR:

Failed to load resource: the server responded with a status of 500 (Internal Server Error) 

POST http://ingleParam.aspx/GetCurrentTime 500 (Internal Server Error) jquery-.11.1.min.js:4
send jquery-1.11.1.min.js:4
m.extend.ajax jquery-1.11.1.min.js:4
ShowCurrentTime SingleParam.aspx:12
onclick

.ASPX Code

function ShowCurrentTime() {
    $.ajax({
        type: "Post",
        url: "SingleParam.aspx/GetCurrentTime",
        data: {     name: $("#<%=txtUserName.ClientID%>").val(), 
                    lastName: $("#<%=txtLastName.ClientID%>").val() },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function (response) {
            alert(response.d);
        }
    });
}

function OnSuccess(response) {
    alert(response.d);
}

Server Side Code:

[WebMethod]
public static string GetCurrentTime(string name, string lastname) {
    return "Hello " + name + Environment.NewLine + "The current time is " + DateTime.Now.ToString();
}

Upvotes: 0

Views: 583

Answers (1)

Smeegs
Smeegs

Reputation: 9224

I've had issues with sending json objects to webmethods. I've had success when I stringify the data being sent across. Like so:

data: JSON.stringify({name: $("#<%=txtUserName.ClientID%>").val(), 
                    lastName: $("#<%=txtLastName.ClientID%>").val()}),

Give that a try and see if it helps.

Upvotes: 1

Related Questions