Friday, October 28, 2011

Invoking Server Side method using Jquery

Hi All,

Recently we had a requirement of performing database operation on the click of a submit button of a web part. In order to avoid post back and trying to implement something new, we tried using jquery for the same.

We used jquery to invoke the server side methods. The methods were defined as web method on an application page (_layouts folder). The web method looked something like this :

[webmethod]
public static void AddNewData(string UserId,string favoriteName, string favoriteURL, string flagmovetoTop)
{
//some business logic
}

Then on the click of the submit button we invoked the java script method, where we performed the data base operations using "JSON". Below is the code snippet for the same.

$(document).ready(function () {
$.ajax({
type: "POST",
url: 'url of the method',
data: "{'userID':'" + userId + "', 'favoriteName':'" + favname + "', 'favoriteURL':'" + favUrl + "','flagmovetoTop':'" + ismovetoTop + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var result = msg.d;
if (result >= 0) {
SubmitClicked();
}
else {

}
}, failure: function (msg) {
// alert(msg);
}
});
});


url : URL parameter is the url of the method used to perform the operation. As mentioned we defined the web methods on the application page so the URL parameter looks something as below :
/_layouts/FolderName/PageName.aspx/AddNewData

One thing which we should keep in mind that if the button is defined on an application page, we need to provide complete url of the method like "http://_layouts/FolderName/PageName.aspx/AddNewData".


data : The data parameter accepts the values of the variables which the web method accepts. The web method which we used accepts four parameters. One thing which we should note that 'UserID', 'favoriteName','favoriteURL' and 'flagmovetoTop' are the name of the parameters defined in the web method.

We were performing database operation and using stored procedure for the same. From the stored procedure we returned '0' if the operation is success else '-1'.

Depending the value returned from the method, the 'result' variable will have value in it. So if it is success (if result ==0) we perform some set of further operation.

Hope this helps.. :)

No comments:

Post a Comment