Waggoner_Keith Waggoner_Keith - 4 months ago 10
PHP Question

Ajax Success Function and Unique Div ids

This is really a two part question. I have a while loop that runs through an SQL query and prints off as many articles as it finds in the database.

<div class='dislike_box'>
<a href='#' class='counter'>
<img src='img/dislike.png' class='vote'></a>
<p class='vote_text'>$dislike_num</p>
<p style='color: #EC2800;'>$dislike_username</p>
</div>

<script>
$('.dislike_box a').click(function(event){
event.preventDefault();
$.ajax({
url: 'vote.php?vote=dislike&title=$title',
success: function(result){
$('.dislike_box p.vote_text').text('Got it.');
}});
});

</script>



  1. The script is in another file. The issue is when the anchor tag is clicked all of the divs p.vote_text on the page gets updated, when I only want to update that specific one.

  2. My second question is, is there a way in the php file to reutrn a value that makes the 'success' function in the ajax method not execute, say for instance they aren't logged in so I don't want them to vote.



Thanks for any help, and I will give credit to a correct answer. Also if you need more info I will be happy to provide it.

I have solved question 2 with returning:

header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
die(json_encode(array('message' => 'ERROR', 'code' => 1337)));


on fail.

EDIT
I have everything working properly except when I run this:

$('.dislike_box a').click(function(event){
event.preventDefault();
var title = $(this).data('title');
alert("You don't like: "+ title);
$.ajax({
url: 'vote.php?vote=dislike&title=title',
success: function(result){
$('.dislike_box p.vote_text').text('Dont Like it.');
}});
});


the alert box displays the correct title but the php function is literally putting the string "title" into the database instead of the variable.

Answer
  1. The way you select the .vote_text is wrong: .dislike_box p.vote_text selects ALL the boxes. Your click function should accept a param so that the a's parent can be targeted.

Let's imagine that you number your questions via id:

the action on your action button should be:

     $('.dislike_box a').click(function(event){
            var parent_question = $(this).closest('.sql_questions');
            event.preventDefault();
            $.ajax({
               url: 'vote.php?vote=dislike&title=$title', 
               success: function(result){
                $(parent_question).text('Got it.');
            }});
     });
  1. It's a PHP question. For the answer to be "fail" you should return a 403 Forbiden access error (https://en.wikipedia.org/wiki/HTTP_403) or some other error.
Comments