In most of the application where frameworks like AngularJS/ React are not being used and simply made with javascript and Jquery, It is important to make use of reusable and generic components which will make things easier for the developer and maintenance.
Advantages:
- A common set of functionalities can be applied to the ajax function call instead of duplicating it through the application.
- Example: request progress event, error handling on failed request.
Implementation:
Code Example: Jquery ajax function is used here.
//generic ajax function var methodTypePost = "POST"; var methodTypeGet = "GET"; function callAjaxMethod(url,method, parameters, successCallback) { try { $.ajax({ type: method, url: url, data: parameters, cache: false, beforeSend : function(){ //enable loader $('.loader').fadeIn(); }, success: successCallback, error: function(xhr, textStatus, errorThrown) { //console.log(errorThrown); $('.loader').fadeOut(); }, complete : function(){ //disable loader $('.loader').fadeOut(); } }); } catch (e) { console.log(e); } };
Ajax Handler used to call ajax events
//common ajax handler to run ajax request var ajaxHandler = function(url, methodType, parameters, func) { function onSuccess(response) { //response = response.trim(); if(response === 'SESSION_EXPIRED'){ alert("Your session is expired. Please login to continue."); window.location.href = 'login.htm?auth=1'; } else func(response); }; try { callAjaxMethod(url, methodType, parameters, onSuccess); } catch (e) { console.log(e); } };
Example how to use this generic ajax event:
//sample code to make ajax call var url = "test.html"; var dataParams = { name : 'hello'}; ajaxHandler(url,methodTypePost,dataParams,function(data) { if(data !== "INVALID_PARAMETERS") { //appropriate feedback to the user. } else { alert("There is a problem on server side. Please try again later."); } console.log(data); });
Now, This common generic function can be included in the common file of the application and from anywhere it can be used to call ajax events.
Feel free to contact me or suggest an appropriate change in this post. I am not the perfect guy.