Search code examples
javascripthtmlbutton

Error when entering information into the database returns the last value loaded


Im working on a project that contains a discussion forum between users with real time updates.

Each message features a 'positive' and 'negative' button. When a button is clicked, I want to store the id of the message.

Instead, my code currently returns the id of the last message that was previously saved.

`var myVar = setInterval(LoadData, 2000);

http_request = new XMLHttpRequest();

function LoadData(){
$.ajax({
 url: 'view.php',
 type: "POST",
 dataType: 'json',
 success: function(data) {
  $('#MyTable div').empty();
  for (var i=0; i<data.length; i++) {
    var commentId = data[i].iddisc;
    if(data[i].parent_comment == 0){

      var date = new Date(data[i].datePubli);
      var hourCycle = date.toLocaleString('es-ES', {hourCycle: 'h23' });

     //In the next line is the development of the positive button

     var row = $('<div class="info-box"><img src="./css/escudos/' + data[i].equipo + '.png" width="25px" height="25px" /><p>' + data[i].username + '</p><p id="date-p"> '+ hourCycle +'</p></div><div class="text-box"><p>' + data[i].post + '</p><div class="posneg"><form name="formpositivo" method="post"><input type="hidden" class="form-posi" name="posCommentid" value="' + commentId + '"><input type="button" id="positivo" name="positivo" class="suma" value="+"></form></div></div>');
    $('#record').append(row);
   }
 }
},
 error: function(jqXHR, textStatus, errorThrown){
 alert('Error: ' + textStatus + ' - ' + errorThrown);
}

}); }`

`//Paso data
$(document).ready(function() {
$(document).on('click', '#positivo', function() {
    var posi = document.forms["formpositivo"]["posCommentid"].value;
        $.ajax({
            url: "positivo.php",
            type: "POST",
            data: {
              posi: posi,
            },
            cache: false,
            success: function(dataResult){
                var dataResult = JSON.parse(dataResult);
                if(dataResult.statusCode==300){
                    alert(posi);
                }
            }
        });
});

});`

Document view

`include './database.php';
$data = array();
$sql = "SELECT *, discussion.id as iddisc, users.id as usersid FROM discussion INNER JOIN users ON discussion.id_user=users.id ORDER BY discussion.id desc";
$result = $conn->query($sql);
while($row = $result->fetch()){
    array_push($data, $row);
    array_push($data);
}

echo json_encode($data);
$conn = null;
exit();`

How can I change this code so that when I click on the corresponding button, the value of the id of the selected message gets returned instead?


Solution

  • As i mentioned in the comment, the problem ocurred because you are using same id to multiple elements inside HTML page which is not recommended. To fix this, you can convert the id positivo to class or you can give any class to the input element on which you can attach event handler.

    So your code in loop becomes.

    var row = $('<div class="info-box"><img src="./css/escudos/' + data[i].equipo + '.png" width="25px" height="25px" /><p>' + data[i].username + '</p><p id="date-p"> ' + hourCycle + '</p></div><div class="text-box"><p>' + data[i].post + '</p><div class="posneg"><form name="formpositivo" method="post"><input type="hidden" class="form-posi" name="posCommentid" value="' + commentId + '"><input type="button" class="positivo suma" name="positivo" value="+"></form></div></div>');
    $('#record').append(row);
    

    Note here that i have changed id positivo to class positivo.

    Now you can attach event handler like below

    $(document).ready(function() {
    $(document).on('click', '.positivo', function() {
        var posi = $(this).parent().find('[name="posCommentid"]').val();
            $.ajax({
                url: "positivo.php",
                type: "POST",
                data: {
                  posi: posi,
                },
                cache: false,
                success: function(dataResult){
                    var dataResult = JSON.parse(dataResult);
                    if(dataResult.statusCode==300){
                        alert(posi);
                    }
                }
            });
    });
    });