<script type="text/javascript"> $(function() { $(".vote").click(function() { var id = $(this).attr("id"); var name = $(this).attr("name"); var dataString = 'id='+ id ; var parent = $(this); if(name=='plus') { $(this).fadeIn(200).html('<img src="/images/upload.gif" align="absmiddle">'); $.ajax({ type: "POST", url: "/pages/up_vote.php", data: dataString, cache: false, success: function(html) { parent.html(html); } }); } else { $(this).fadeIn(200).html('<img src="/images/upload.gif" align="absmiddle">'); $.ajax({ type: "POST", url: "/pages/down_vote.php", data: dataString, cache: false, success: function(html) { parent.html(html); } }); } return false; }); }); </script> 

 echo '<span><a href="" class="vote" id="'.$rowcomments['id'].'" name="plus">+</a></span>'; 

And handler

 require_once '../system/core.php'; if($_POST['id']) { if($row['id_user']==$user['id'] && $user['level']<2 && $articles['pobeda']==0) { echo 'Вы уже голосовали за данный комментарий! Голосовать можно только один раз!'; exit; } $articles = mysql_fetch_assoc(mysql_query("SELECT * FROM `articles_comments` WHERE `id`='".$id."'")); $row = mysql_fetch_assoc(mysql_query("SELECT * FROM `articles_comments_reputation` WHERE `id_comments`='".$id."'")); mysql_query("UPDATE `articles_comments` SET `golosov` = '".intval($articles['golosov']-1)."' WHERE `id` = '".$articles['id']."'"); mysql_query("INSERT INTO `articles_comments_reputation` SET `id_user` = '".$user['id']."', `id_articles` = '".$articles['id_articles']."', `id_comments` = '".$id."', `type` = 'minus', `time` = '".$realtime."'"); exit; } 

The problem is that the result is displayed after I refresh the page and, moreover, for some reason, 2 votes are added / withdrawn at once. Can someone help?

  • how js is loaded? check the contents of intval ($ articles ['golosov'] - 1) - FLK

1 answer 1

Sit back - I'll write a lot))

- To begin with, there is one question:

 // Откуда берется переменная $id? Например, тут: SELECT * FROM `articles_comments` WHERE `id`='".$id."' // Что-то вроде - $id = $_POST['id']; - выше по коду, я не увидел 

- On the other hand, it was striking that you are using the $ row ['id_user'] variable in comparison before you get the result in $ row from the query to the database:

 $row = mysql_fetch_assoc(mysql_query("SELECT * FROM `articles_comments_reputation` WHERE `id_comments`='".$id."'")); 

I can say the same about verification using the $ articles ['pobeda'] variable

- An absolute mystery remains for me to request

 $row = mysql_fetch_assoc(mysql_query("SELECT * FROM `articles_comments_reputation` WHERE `id_comments`='".$id."'")); 

and the wonderful phenomenon of the $ realtime variable, although the latter can be taken from the core.php file

- Further ... Based on the fact that there is a check of the name variable (in the JS-part), I can assume that in addition to the plus value, there is also the value of ala minus . In each case, there are ajax-requests (identical in essence!) And their handlers, which also perform exactly the same actions, with the only fundamental difference that in the first case, the value of the golosov field is increased by one, and in the second - decreases.

- Continuing the analysis of the flight in the ajax part - what do you want to receive in response? And what kind of data do you want to get? Besides

 echo 'Вы уже голосовали за данный комментарий! Голосовать можно только один раз!'; 

I watch nothing. One would assume that this is what you need if you didn’t say that the problem is that the result is not immediately visible, but I would like ... I think so)) By the way, what is the result would you like to see ?!

I probably don’t know any particular nuances, but, having missed the subtleties, I’ll try to define the task like this:

When you click on the + or - button, you need to increase / decrease the number of votes (in the database) for a particular article and output the final result to the user - the total number of votes on this article.

I suggest to try this:

JS (combine voting processing)

 $(function() { $('.vote').click(function(e) { e.preventDefault(); var articleId = $(this).attr('id'); // ID статьи var voteValue = $(this).attr('name'); // голос "ЗА" или "ПРОТИВ" var parent = $(this); $(this).fadeIn(200).html('<img src="/images/upload.gif" align="absmiddle">'); $.ajax({ type: 'POST', url: '/pages/handler_vote.php', data: {aid: articleId, vVal: voteValue}, success: function(data){ // в data[0] - значение $success // в data[1] - значение $response if(data[0]){ parent.html(data[1]); } else { alert(data[1]); } }, dataType: 'json' }); }); }); 

PHP (! One handler_vote.php handler)

 if(isset($_POST['aid'])){ // Проверку на "право голоса" и последний запрос (INSERT) сделаете сами if(/* если права голоса нет */){ $response = 'Вы уже голосовали за данный комментарий! Голосовать можно только один раз!'; $success = false; } else { $aid = mysql_real_escape_string($_POST['aid']); $voteValue = mysql_real_escape_string($_POST['vVal']); // Вместо проверки ниже, можно значения "1" и "-1" хранить вместо "plus" и "minus" в атрибуте "name" if($voteValue == 'plus'){ $vote = 1; } else { $vote = -1; } // Увеличиваем или уменьшаем кол-во голосов $resUpd = mysql_query("UPDATE `articles_comments` SET `golosov` = `golosov` + '".$vote."' WHERE `id` = '".$aid."'"); // Проверку на то, что проапдейтилось или нет - на ваше усмотрение if($resUpd){ $resSel = mysql_query("SELECT * FROM `articles_comments` WHERE `id`='".$aid."'"); $articles = mysql_fetch_assoc($resSel); /* что-то еще делаете свое */ $response = $articles['golosov']; // Итоговое количество голосов $success = true; } else { $response = 'Хьюстон! У нас проблемы!!! Апдейт потерян!'; $success = false; } } // Подготавливаем ответ echo json_encode(array($success,$response)); exit(); } 
  • Some questions too much. This is if ($ row ['id_user'] == $ user ['id'] && $ user ['level'] <2 && $ articles ['pobeda'] == 0) {echo 'You have already voted for this comment ! You can vote only once! '; exit; } just lower below. I would like to immediately see the result of the vote. On the comments page, it is displayed like this: echo '<span>'. $ All_rat_comments. '</ Span>'; In general, counted the number of negative, positive reviews, from the number of positive we subtract the number of negative and deduce. In the golosov field is written the total number of votes for the comments (added or subtracted) to sort the comments. - vitagame
  • So it works, just added a little something. But it would not be bad to make the removal of the number of votes, since it is displayed and deletes the reference to the minus if the vote is positive and vice versa. And why = it is still 2 votes added / subtracted. And by the way about the ID - $ id = isset ($ _REQUEST ['id'])? abs (intval ($ _ REQUEST ['id'])): false; - vitagame
  • So you had a lot of incomprehensible things in the question, but now there are even more mysteries. You have a simple task, but you somehow managed to complicate it. I can assume that some of the problems arise because of a not properly designed database structure, the problem is still 2 voices added / subtracted - maybe because of the wrong sequence of operations in the script. Guessing what and why can be long. - Deonis
  • @vitagame, move away from mysql_ * in the direction of PDO, MySQLi etc. - Arseniy
  • Yes, it would be necessary. - vitagame