I have a question, and I don't know if I'm posting it on the right place of the forum. I'm trying to do a form with Ajax to count my clicks through Ajax. But the problem is that every time I do a click I always receive the number of clicks as 1.
Here's a piece of the code explained:
In JavaScript from the View
$("#click").click(function(){
$.ajax({
type: "POST",
url: bseUrl+"counter/incCount",
data: click,
success: function(html){
alert(html);
}
});
});
The alert(html) should show the total clicks from the server;
counter controller
class Counter extends CI_Controller {
//put your code here
var $numClick;
public function __construct() {
parent::__construct();
$this->numClick= 0;
}
public function Counter() {
parent::__construct();
$this->numClick= 0;
}
public function incCount() {
echo $this->numC开发者_JS百科lick++;
}
public function index() {
//loadView
}
}
But every time I click I'm always receiving the number of clicks as 1. Why am I losing the variable content every time? it seems that every time I do a Ajax call I'm starting the variable.
Can you guys help me?
You are re-initializing the counter every time you call click handling function - why? try doing it this way:
//init counter somewhere
var num_clicks= 0;
//increase counter and send request
$("#click").click(function(){
num_clicks++;
var click= "numberClick="+num_clicks;
$.ajax({
type: "POST",
url: bseUrl+"counter/incCount",
data: click,
success: function(html){
alert(html);
}
});
});
精彩评论