How to put ajax request inside function and call it when necessary?

Viewed 1921

I have an ajax request:

$.ajax({
type: 'POST',
url: '/get-result.php',
dataType: 'json',
data: 'pid=' + $(this).attr("id"),
success: function(response) {
$(".reviewee-fname").append(response['fname']);
$(".reviewee-lname").append(response['lname']);
    }     }); };

I want to be able to put this inside a function that waits for me to trigger it with a return call. I am not exactly sure how to word it, I am new to javascript and jquery. But basically, I want to trigger this ajax call with various different button clicks and instead of having to put the ajax call inside every button click event, I want to put it in a stand alone function so if I ever update it later I dont have to change it 5 times.
Heres an example of a click event Id like to call the ajax request function with. Thanks!

$(function() {
$(".task-listing").click(function() {
//Call Ajax function here.
});
});
2 Answers

Callbacks are well-suited for this scenario. You can encapsulate your ajax call in a callback function.

function apiCall() {
$.ajax({
type: 'POST',
url: '/get-result.php',
dataType: 'json',
data: 'pid=' + $(this).attr("id"),
success: function(response) {
$(".reviewee-fname").append(response['fname']);
$(".reviewee-lname").append(response['lname']);
    }     }); };
}

You can now hook apiCall()method as a callback to button click.

$(function() {
$(".task-listing").click(apiCall);
});

By doing this you will able to achieve this.

I want to put it in a stand alone function so if I ever update it later I dont have to change it 5 times.

EDIT:

Note:

This is lead to start, you can alter this according to your requirement.

Is this not working for you? ↓↓

$(function() {
    $(".task-listing").click(function() {
        let pid = $(this).attr("id"); //get any other value which you want to pass in function, say url
        someFunction(pid);  // pass any other parameters, eg- someFunction(pid, url)
    });
});

function someFunction(pid){  // someFunction(pid, url)
    $.ajax({
        type: 'POST',
        url: '/get-result.php', // url: url
        dataType: 'json',
        data: 'pid=' + pid,
        success: function(response) {
            $(".reviewee-fname").append(response['fname']);
            $(".reviewee-lname").append(response['lname']);
        }     
    }); 
}
Related