javascriptphpjqueryajax

Variable passing to JavaScript function is not changing


I'm trying to implement a feature for reporting a comment on a site. I'm using PDO and have the function in a PHP class.

When clicking 'report' a JS function is called that uses Ajax to then call the PHP function that'll update the database / email the admin.

I can't see why but the id getting passed to the JS is always the same.

I've done various outputs to test and within the HTML the id is correct. There are currently 3 different ones that I'm testing. When I alert the id in the function it is always the same.

Any help is much appreciated.

The HTML:

<? foreach ($comments as $c){
   $commentId = $c['id']; ?>
     <p><a href="#" id="report" name="report" data-value="<?php echo $commentId ?>" onclick="reportComment(); return false;">Report?</a></p>
<? } ?>                 

The JS:

function reportComment(){

var id = $('#report').attr('data-value');
var url = "/Perspect/commentsAjax/report.php";
var params = {id: id};

$.ajax({
    cache: false,
    type: 'POST',
    url: url,
    data:params,
    dataType:'json',

    success: function(){
        alert("sucess");
        //change ahref to say this comment has been reported
    },
    error: function(error){
        console.log(error);
    }
});
alert("ID" + id);
}

PHP:

<?php include '../core/init.php';

if($_POST){
  $id = $_POST['id'];
  $articleComments->reportComment($id);
}
?>

Solution

  • The problem is that all of your links share the same id="report", so you can't access a single one of them (but JS will automatically select the first appearence). This could be resolved by simply passing the id as a parameter.

    <p><a href="#" name="report" onclick="reportComment(<?php echo $commentId; ?>); return false;">Report?</a></p>
    //...
    function reportComment(id){
    

    When you want to manipulate the element after the click, you can do it like the following

    <? foreach ($comments as $c){
       $commentId = $c['id']; ?>
         <p><a href="#" id="report_<?php echo $commentId ?>" name="report" onclick="reportComment(<?php echo $commentId ?>); return false;">Report?</a></p>
    <? } ?>
    

    Now you have unique ids report_1, report_2 etc. and your JS could be like the following

    function reportComment(id){
        //do your stuff
        $("#report_"+id).text("already reported");
    

    As was suggested in the comments of your question, this can also be solved using only JavaScript (by the help of jQuery), you wouldn't need the onclick logic in your HTML

    <a class="report" data-value="1">report</a>
    <a class="report" data-value="2">report</a>
    

    and this could be the JS

    $(".report").click(function(){
        var id = $(this).attr('data-value');
        //do your magic
        $(this).text('already reported');
    });