Tag Archives: JQuery

Code Optimization for Ajax JQuery Web Request

When we use ajax calls for consuming web methods we use the following method.

$.ajax({
type: “POST”,
url: url,
data: JSON.stringify(params),
contentType: “application/json; charset=utf-8”,
dataType: “json”,
success: function (result) {
if (result == null || result == undefined || result.d.trim() == ”) return;
successFunc(JSON.parse(result.d), targetObj);
},
failure: function (error)
{ }
});

 

But to use this code on each page and for each web method call is a repetition of  code and we can avoid that if we define it at one place and then consume it from there every time we need to use it.

One way of doing it is to enclose the code in a function like this below.

function ajax_data_loader(url, params, successFunc, targetObj) {
$.ajax({
type: “POST”,
url: url,
data: JSON.stringify(params),
contentType: “application/json; charset=utf-8”,
dataType: “json”,
success: function (result) {
if (result == null || result == undefined || result.d.trim() == ”) return;
successFunc(JSON.parse(result.d), targetObj);
},
failure: function (error)
{ }
});
}

So wherever we need to use it we only need to call the function with the appropriate parameters.

ajax_data_loader(‘FleetInspectionAnalysis.aspx/GetTreeFirstLevel’,{customer_auto:customer_auto},load_firstlevel,$(‘#fleet_tree’));

 

 

Advertisements