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

One thought on “Code Optimization for Ajax JQuery Web Request

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s