enjaku enjaku - 2 months ago 10
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) {
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?


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() {

or Another method

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

function firstScanStatIncrement(event){