Friday, February 20, 2015

AJAX call from Visual Web Part - SharePoint

1)
In the JavaScript function create the JSON object. Here the stringify method is used to construct the object which contains the parameters to be sent. The function in the JavaScript method of the aspx page is as below:


    function CallMyPage(itemValue, paramTwo, paramThree, paramFour) {

        var final = { myItem: itemValue, parameterTwo: paramTwo, parameterThree: paramThree, siteUrl: paramFour };

        $.ajax({
            type: "POST",
            url: paramFour + "/_layouts/15/MyFeatureFolder/WebMethods.aspx/MyWebMethod",
            data: JSON.stringify(final),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
           failure: function (response) {
             alert(response.d);
          }
       });
    }

2)
In the code behind within a SPGridView I have a HyperLink control. I set the JavaScript method call in the code behind as:

editLink.NavigateUrl = "javascript:CallMyPage('" + itemGuid.Text + "','" + MyParamTwo + "' ,'" + MyParamThree + "', '" + SPContext.Current.Web.Url + "');"


3)
In my approach instead of a web service I am using an application page (WebMethods.aspx) to get the job done. In the application page servicing the AJAX call, I create the web method

        [System.Web.Services.WebMethod]
        public static string MyWebMethod(string myItem, string parameterTwo, string parameterThree, string siteUrl)
        {
            string result = string.Empty;
            try 
            {
                //TODO - Process request and return result
            }
            catch (Exception)
            {
                //Exception Handling
            }
            return result;

4)
On success

    function OnSuccess(response) {

        if (response.d) {           
            /* Handle  result */            
        }
    }

Note: I have used the jquery-1.11.2.min.js file in my solution

No comments:

Post a Comment