Friday, March 20, 2015

AJAX Call Handling Function

Ajax Call Handling Function


Here is the better way to have ajax call and the way to manage its  results, write the below standard function as shown in any one place of JS or make it as separate script and include ==>

/*--Core Ajax Handling----------------------------------*/
/*------------------------------------------------------*/
function AjaxCall(pagePath, fn, paramArray, successFn, errorFn) {
    if (pagePath.length == 0)
        pagePath = window.location.pathname;
    //Create list of parameters in the form: 
    //{"paramName1":"paramValue1","paramName2":"paramValue2"} 
    var paramList = '';
    if (paramArray.length > 0) {
        for (var i = 0; i < paramArray.length; i += 2) {
            if (paramList.length > 0) paramList += ',';
            paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] 
            + '"';
        }
    }
    paramList = '{' + paramList + '}';
    //Call the page method  
    $.ajax({
        type: "POST",
        url: pagePath + "/" + fn,
        contentType: "application/json; charset=utf-8",
        data: paramList,
        dataType: "json",
        success: successFn,
        error: errorFn
    });
}




Usage in JS Script==> 

//Calling method
//pagePath (pass empty), parameters (can pass as many as you required),success fn , fail fn
AjaxCall("", "CodeBehindMethod", ["strParm1", "1","strParm1""1"], successFunctionName, FailureFunctionName);



//Success function Logic can be handled here
function successFunctionName (msg) 
{
  if (msg.d != null
  { 
     //Logic
  } 
  else
  { 
   alert('No results found');
  }
}

//If Fails then it can be handled here
function FailureFunctionName (msg)
  alert(msg.d);  
}



Code Behind (.cs Logic) WebMethod

// It should have an attribute WebMethod
[WebMethod]
public static string CodeBehindMethod(string strParm1, string strParm2)
{
try
{
//Logic
//Logic
//Logic
//Logic
return "Success";

}
catch (Exception ex)
{
      return "Error";
}
}

No comments: