Reusable ajax js template (jquery)

I would like to know if there is a better approach to creating a reusable ajax object for jquery.

This is my incomplete code.

var sender = { function ajax(url, type, dataType, callback) { $.ajax({ url: url, type: type, dataType: dataType, beforeSend: function() { onStartAjax(); }, error: function(XMLHttpRequest, textStatus, errorThrown) { callback.failure(XMLHttpRequest, textStatus, errorThrown); }, success: function(data, textStatus) { callback.success(data, textStatus); }, complete: function (XMLHttpRequest, textStatus) { onEndAjax(); } }); }, function onStartAjax() { // show loader }, function onEndAjax() { // hide loader } }; <script type="text/javascript"> var callback = { success: function(data, textStatus) { $('#content').html(data); }, failure: function(XMLHttpRequest, textStatus, errorThrown) { alert('Error making AJAX call: ' + XMLHttpRequest.statusText + ' (' + XMLHttpRequest.status + ')'); } } sender.ajax(url, type, dataType, callback); </script> 
+6
javascript jquery design-patterns
source share
3 answers

You can set the basic parameters that you always use the same way.

if you always use the same thing:

  type: type, dataType: dataType, 

for these types, you can install them separately.

Here's how you do it:

 $.ajaxSetup({ type: "POST", contentType: "application/json; charset=utf-8", data: "{}" }); 

NOW they are installed and you can simplify your individual ajax calls.

EDIT:

NOTE. Setting parameters in $ .ajax overrides these default values. Thus, pre-setting β€œdata” to an empty JSON string is safe and desirable. Thus, any call to $ .ajax that sets the data parameter will function properly, since the default value will not be used. This helps to avoid problems that can be difficult to find on a deployed site.

+4
source share

Here is what I did:

 var ajaxclient = (function (window) { function _do(type, url) { return $.ajax({ url:url, type:type, dataType:'json', beforeSend: _onStartAjax }).always(_onEndAjax); } function _onStartAjax() { console.log("starting ajax call"); } function _onEndAjax() { console.log("finished ajax call"); } return { do:_do } }(this)); 

Usage example:

 ajaxclient.do("get","http://...").done(function(data) {console.log(data);}) 
+3
source share

I would probably go all the hog and create an Ajax Object.

 var ajax = new MySuperAjax(url, data); ajax.onComplete = function(){} 

or similar. It seems you are halfway between a function that has some default values ​​that it extends, with the ones you use and the object for it.

+1
source share

All Articles