enjaku enjaku - 1 month ago 8
Javascript Question

javascript/jquery function is called on page load instead of onclick

I have a function which sends data to a server using ajax:

function firstScanStatIncrement(a) {
$.ajax({
url: "/my_url",
type: "get",
data: {
attr: a,
report_action: "report_action"
}
});
}


and I want to call the function when specific button is clicked. I do it like this:

$("#to-my-account").on("click", firstScanStatIncrement("account_page"));


but the function is called right after my page has been loaded. What do I do wrong?

Answer

In your code

$("#to-my-account").on("click", firstScanStatIncrement("account_page"));

immediately call the callback function in your context. So the ajax call runs on the page load without clicking the dom element.

Call the callback after the dom element click and your code be like

$("#to-my-account").on("click", function() {
    firstScanStatIncrement("account_page");
});

or Another method

$("#to-my-account").click({param: "account_page"}, firstScanStatIncrement);

function firstScanStatIncrement(event){
    alert(event.data.param);
}