Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 445
Ryan Avatar asked Dec 11 '25 03:12

Ryan


1 Answers

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({});
});
like image 78
Wilmer Avatar answered Dec 13 '25 17:12

Wilmer