Reputation: 1065
Hi I have a function that makes ajax calls once an element is clicked. I use this code:
$(document).ready(function()
{
function ajax_call(offset, length) {
$.ajax({method: "get",
url: "file.php",
data: "offset="+ offset,
success: function(returnedData)
{
$("#content").html(returnedData);
}
});
}
$("#profile").click(ajax_call(0, 1000));
});
The issue is with this line:
$("#profile").click(ajax_call(0, 1000));
When I pass arguments to ajax_call function, the function is run once the page loads without any user intervention, however when I remove the arguments like this:
$("#profile").click(ajax_call);
the function is called only when the element is clicked. I have researched for hours about this issue but with no luck
Upvotes: 0
Views: 342
Reputation: 816700
This will call the function immediately ajax_call(0, 1000)
and pass the return value as event handler.
You have to wrap it in an anonymous function:
$("#profile").click(function() {
ajax_call(0, 1000);
});
Whenever you have functionname()
you are actually calling the function. functionname
instead (without parenthesis) gives you a reference to the function. As you cannot just pass ajax_call
to click
, you have to wrap it in another function.
So the anonymous function function(){...}
is passed as event handler and when it gets called, it executes ajax_call(0, 1000)
.
Upvotes: 1