Generic Ajax function using jQuery

I saw developers generally write number of lines of code to achieve ajax functionality in projects. Due to this the code duplication occurs at different parts of application and this leads to maintenance problem as well as number of lines of code also increase the page size and decrease the performance of particular page.

To overcome this, I would suggest developers to write the generic functions to achieve ajax functionality. In below javascript code snippet I have created one common file Common.js and referred to my master page in application.

Step 1: Create Common.js file and copy paste below code in it and refer onto your page or master page(recommended)

 

Common.js
var Common = {
    Ajax: function (httpMethod, url, data, type, successCallBack, async, cache) {
        if (typeof async == "undefined") {
            async = true;
        }
        if (typeof cache == "undefined") {
            cache = false;
        }

        var ajaxObj = $.ajax({
            type: httpMethod.toUpperCase(),
            url: url,
            data: data,
            dataType: type,
            async: async,
            cache: cache,
            success: successCallBack,
            error: function (err, type, httpStatus) {
                Common.AjaxFailureCallback(err, type, httpStatus);
            }
        });

        return ajaxObj;
    },

    DisplaySuccess: function (message) {
        Common.ShowSuccessSavedMessage(message);
    },

    DisplayError: function (error) {
        Common.ShowFailSavedMessage(message);
    },

    AjaxFailureCallback: function (err, type, httpStatus) {
        var failureMessage = 'Error occurred in ajax call' + err.status + " - " + err.responseText + " - " + httpStatus;
        console.log(failureMessage);
    },
	
    ShowSuccessSavedMessage: function (messageText) {

 //use jquery BlockUI library to display message

        $.blockUI({ message: messageText });
        setTimeout($.unblockUI, 1500);
    },

    ShowFailSavedMessage: function (messageText) {

	 //use jquery BlockUI library to display message

        $.blockUI({ message: messageText });
        setTimeout($.unblockUI, 1500);
    }
}

 

Step 2: How will you use above file

 

The above function can be useful to POST, PUT, DELETE and GET functions of ajax.  Let’s see the scenario to POST data to server using ajax function

 

function saveData() {

    //Do form validations if any
    var isValidForm = ValidateForm('formUser');

    var url = '';
    var dataToPost = $('#formUser').serialize(); // 

    if (parseInt($('#Id').val()) > 0) {
        url = 'User/Update'; // MVC Action Name
    }
    else {
        url = 'User/Create'; // MVC Action Name
    }

    // For Post Method
    Common.Ajax('POST', url, dataToPost, 'json', successUserCreateHandler);
}

function successUserCreateHandler(response) {
    if (response.type == 'Success') {
        Common.DisplaySuccess('Employee details saved successfully.');
    }
}

 

For Getting data from server use below code.

 

function GetData(id) {
    var url = 'User/Edit';
    var param = { id: id };

    Common.Ajax('GET', url, param, 'html', openPopupSuccessHandler);
}

function openPopupSuccessHandler(response) {
    //set html/response to element otherwise processing logic..
}

 

That’s it !!

 

Leave a Reply