0

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?

enjaku
  • 326
  • 4
  • 17

2 Answers2

2

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);
}
Sudharsan S
  • 15,336
  • 3
  • 31
  • 49
1

It's because you need to pass function as event handler but you call this function instead of passing.

This should work:

$("#to-my-account").on("click", firstScanStatIncrement.bind(window, "account_page"));
Eugene Tsakh
  • 2,777
  • 2
  • 14
  • 27