I am using the following (added to DOM code) to update a MySQL db with like data, but, its posting twice and I have no clue why.
I have almost identical code for unlike which also posts twice so it kind of cancels itself out but twice as many DB hits than needed is never good.
html += '<script type="text/javascript">';
html += '$(function()';
html += '{';
html += '$(".like").click(function(){';
html += 'var element = $(this);';
html += 'var I = element.attr("id");';
html += 'var info = \'article_id=\' + I;';
html += '$.ajax({';
html += 'type: "POST",';
html += 'url: "/pages/includes/ajax/like.php",';
html += 'data: info,';
html += 'success: function(){';
html += '$(\'#like\'+I).fadeOut("fast");';
html += '$(\'#unlike\'+I).fadeIn("slow");';
html += '}';
html += '});';
html += 'return false;';
html += '});';
html += '});';
html += '</script>';
How can I avoid posting twice?
Your click event will execute the same anonymous function multiple times if the code was added to the dom in multiple places. So make sure this code doesn’t appear more than once in your page source.