Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make many jQuery ajax calls look pretty?

I'm making many ajax call based web service. I attached event listeners every dom elements. And every event handlers request ajax call in it. By the way, my source code getting more dirty and complexity. I want to reduce boilerplate code and look more simple with ajax calls.

How can I do that effectively?

The sample code looks like this:

<a href="javascript:void(0);" class="button1">button1</a>
<a href="javascript:void(0);" class="button2">button2</a>
<a href="javascript:void(0);" class="button3">button3</a>
<a href="javascript:void(0);" class="button4">button4</a>

$('.button1').on('click', function() {
    $.ajax({
        url: '/api/1/resource1',
        data: {
            value1: 'value1',
            value2: 'value2'
        },
        success: function (response) {
            $('.some_dom1').html(Handlebars.resource({items:response.items}));
        }
    });
});

$('.button2').on('click', function() {
    $.ajax({
        url: '/api/1/resource2',
        data: {
            value1: 'value1',
            value2: 'value2'
        },
        success: function (response) {
            $('.some_dom2').html(Handlebars.resource({items:response.items}));
        }
    });
});

$('.button3').on('click', function() {
    $.ajax({
        url: '/api/1/resource3',
        data: {
            value1: 'value1',
            value2: 'value2'
        },
        success: function (response) {
            $('.some_dom3').html(Handlebars.resource({items:response.items}));
        }
    });
});

$('.button4').on('click', function() {
    $.ajax({
        url: '/api/1/resource4',
        data: {
            value1: 'value1',
            value2: 'value2'
        },
        success: function (response) {
            $('.some_dom4').html(Handlebars.resource({items:response.items}));
        }
    });
});

Updated:

Every class name and ajax response handler is not same each other. Example code just shows boilerplate code and complexity. This is not the problem of class name or if else statements.

like image 835
gentlejo Avatar asked Feb 24 '15 06:02

gentlejo


2 Answers

Make common function like this:

String.prototype.endsWith = function(suffix) {
   return this.indexOf(suffix, this.length - suffix.length) !== -1;
};

var doAjax_params_default = {
    'url': null,
    'requestType': "GET",
    'contentType': 'application/x-www-form-urlencoded; charset=UTF-8',
    'dataType': 'json',
    'data': {},
    'beforeSendCallbackFunction': null,
    'successCallbackFunction': null,
    'completeCallbackFunction': null,
    'errorCallBackFunction': null,
};


function doAjax(doAjax_params) {

    var url = doAjax_params['url'];
    var requestType = doAjax_params['requestType'];
    var contentType = doAjax_params['contentType'];
    var dataType = doAjax_params['dataType'];
    var data = doAjax_params['data'];
    var beforeSendCallbackFunction = doAjax_params['beforeSendCallbackFunction'];
    var successCallbackFunction = doAjax_params['successCallbackFunction'];
    var completeCallbackFunction = doAjax_params['completeCallbackFunction'];
    var errorCallBackFunction = doAjax_params['errorCallBackFunction'];

    //make sure that url ends with '/'
    /*if(!url.endsWith("/")){
     url = url + "/";
    }*/

    $.ajax({
        url: url,
        crossDomain: true,
        type: requestType,
        contentType: contentType,
        dataType: dataType,
        data: data,
        beforeSend: function(jqXHR, settings) {
            if (typeof beforeSendCallbackFunction === "function") {
                beforeSendCallbackFunction();
            }
        },
        success: function(data, textStatus, jqXHR) {    
            if (typeof successCallbackFunction === "function") {
                successCallbackFunction(data);
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            if (typeof errorCallBackFunction === "function") {
                errorCallBackFunction(errorThrown);
            }

        },
        complete: function(jqXHR, textStatus) {
            if (typeof completeCallbackFunction === "function") {
                completeCallbackFunction();
            }
        }
    });
}

then in your code:

$('.button').on('click', function() {
  var params = $.extend({}, doAjax_params_default);
  params['url'] = `your url`;
  params['data'] = `your data`;
  params['successCallbackFunction'] = `your success callback function`
  doAjax(params);
});
like image 55
rsudip90 Avatar answered Oct 12 '22 08:10

rsudip90


Use a common class:

<a href="javascript:void(0);" class="button">button1</a>
<a href="javascript:void(0);" class="button">button2</a>
<a href="javascript:void(0);" class="button">button3</a>
<a href="javascript:void(0);" class="button">button4</a>

add listener to this class:

$('.button').on('click', function() {
//find the index of the element and use it 
    var btnNumber= $( ".button" ).index(this)+1;

    $.ajax({
        url: '/api/1/resource'+btnNumber,
        data: {
            value1: 'value1',
            value2: 'value2'
        },
        success: function (response) {
            $('.some_dom'+btnNumber).html(Handlebars.resource({items:response.items}));
        }
    });
});

You can also use any kind of attribute and use it later for any data or parameter

like :

<a href="javascript:void(0);" abc="hello1" class="button">button1</a>
<a href="javascript:void(0);" abc="hello2" class="button">button2</a>
<a href="javascript:void(0);" abc="hello3" class="button">button3</a>
<a href="javascript:void(0);" abc="hello4" class="button">button4</a>

and then use it for any purpose

$('.button').on('click', function() {
    var dVal=$(this).attr('abc');
//use dVal any where you want.
    alert(dVal);

});
like image 24
Saif Avatar answered Oct 12 '22 08:10

Saif