Counter is updated only once despite clicks
I'm trying to build a counter where the admin user of the web site may update a counter by clicking a link. When the user clicks the counter link $.get sends the data to a mySQL record and the record is updated. The number is then sent back to Jquery which updates the counter without refreshing. Up to this point everything works.
The problem happens when the user clicks more than once. The MySQL record is updated correctly but the counter is updated only the first time the user clicks the link. Here's my code:
<div class='counter' id='4592'><a href=''>Counter: 24</a></div>
$.get("jquery.php", { id: $(this).attr('id'), counter: 'increase' },
function(data) {
$('.counter').replaceWith('<div class="counter" id="' + $(this).attr('id') + '"><a href="">Counter: ' + data + '</a></div>');
}
);
PHP:
$id = $_GET['id'];
$num = $_GET['counter'];
switch ($num) {
case 'increase':
// ---- Before updating the record get the number sa开发者_C百科ved in the database
$qry = mysql_query("SELECT counter FROM table WHERE id='".$id."'") or die(mysql_error());
$number = mysql_fetch_array($qry);
$n = $number['counter'];
// ---- Increase the counter and update the record
$a = $n + 1;
mysql_query("UPDATE table SET counter = '".$a."' WHERE id = '".$id."'");
// --- Send data back
echo "Counter: ".$a;
break;
}
$.get
requests are cached by default, so every subsequent request is not actually goes to the server. Use $.ajax
request passing cache: false
as a parameter or use ajaxSetup
to turn off caching globally.
Few queries -
1. $(this).attr('id') does it work on the callback. Are you getting the correct id ?
2. Replace with replaces the content. Why are you adding the div again to counter ?
3. This should work fine :-
$('.counter').replaceWith('<a href="">Counter: ' + data + '</a>');
You should setup the defaults of your $.get jquery method for cache:
$.get = function(url, callback) {
$.ajax({
async : false,
type: "GET",
url: url,
success: callback,
cache: true
});
};
The other method is using that:
$.ajaxSetup({cache : true});
$.get(...);
$.ajaxSetup({cache : false});
精彩评论