Geeth Welagedara Geeth Welagedara - 3 months ago 7
jQuery Question

How to avoid duplicate calling for javascript function

Following

javascript
has
getAjax
function. which was call every mouse select event in the html form. I have to call same function in each event. When i want to modify
getAjax
function, have to do for all event. Is there any way to keep
getAjax
function one place and call in each mouse event.

Note : all select elements are in the same container



<script type = "text/javascript" >
$(document).ready(function() {
var age1 = 21;
var age2 = 35;
var salary = 10000;
var width = 410;
var height = 510;
getAjax(ajaxUrl, salary, age1, age2, width, height);
$("#age1").change(function() {
age1 = parseInt($(this).val());
getAjax(ajaxUrl, salary, age1, age2, width, height);
});
$("#age2").change(function() {
age2 = parseInt($(this).val());
getAjax(ajaxUrl, salary, age1, age2, width, height);
});
$("#salary").change(function() {
salary = parseInt($(this).val());
getAjax(ajaxUrl, salary, age1, age2, width, height);
});
$("#width").change(function() {
width = parseInt($(this).val());
getAjax(ajaxUrl, salary, age1, age2, width, height);
});
$("#height").change(function() {
height = parseInt($(this).val());
getAjax(ajaxUrl, salary, age1, age2, width, height);
});
});

function getAjax(URL, salary, age1, age2, width, height) {
$.ajax({
url: URL,
data: {
sala: salary,
age1: age1,
age2: age2,
het1: width,
het2: height
},
dataType: "html",
type: "POST",
success: function(retdata) {
$("#data1").html(retdata);
}
});
} </script>




Answer

You can combine the selector and you could rewrite the variables, maybe into an object, which make everything more compact.

$(function() {
    var data = {
        age1   : 21,
        age2   : 35,
        salary : 10000,
        width  : 410,
        height : 510
    };

    getAjax(ajaxUrl, data.salary, data.age1, data.age2, data.width, data.height);

    $("#age1, #age2, #salary, #width, #height").change(function() {
        data[$(this).attr("id")] = parseInt($(this).val());
        getAjax(ajaxUrl, data.salary, data.age1, data.age2, data.width, data.height);
    });
});

Even better would be if you change your getAjax function to work with the object too. This will save you even more code.

$(function() {
    var data = {
        age1   : 21,
        age2   : 35,
        salary : 10000,
        width  : 410,
        height : 510
    };

    getAjax(ajaxUrl, data);

    $("#age1, #age2, #salary, #width, #height").change(function() {
        data[$(this).attr("id")] = parseInt($(this).val());
        getAjax(ajaxUrl, data);
    });
});

function getAjax(URL, data) {
    $.ajax({
        url: URL,
        data: data,
        dataType: "html",
        type: "POST",
        success: function(retdata) {
            $("#data1").html(retdata);
        }
    });
} 
Comments