Search code examples
jqueryajaxfunctionreusability

Reusing AJAX function multiple times


Currently my AJAX call is set up as such so that when a comma keyup is detected, the AJAX call fires:

$("#selector").on("keyup", function(e) {
    if (e.which === 188) {

        var search = $(this).val();

        function searchTag() {
            return $.ajax({
                cache:      false,
                url:        url,
                dataType:   "json",
                type:       "post",
                data:       {search: search}
            });             
        }

        searchTag().done(function(data) {
            //Success
        });
    }
});

I want to reuse the AJAX call as part of another event listener later in my code:

$("body").on("click", ".tag", function () {
    searchTag();
});

Without rewriting the entire call, how do I make the function independent so that it can be used in both scenarios?


Solution

  • Move the function outside:

    function searchTag(data) {
        var url = "yoururl";
        return $.ajax({
            cache:      false,
            url:        url,
            dataType:   "json",
            type:       "post",
            data:       data
        });             
    }
    
    $("#selector").on("keyup", function(e) {
        if (e.which === 188) {
    
            var search = {search: $(this).val()};
    
    
            searchTag(search).done(function(data) {
                //Success
            });
        }
    });
    
    $("body").on("click", ".tag", function () {
        searchTag({});
    });