Skip to content
Advertisement

Ajax call dynamically loaded rows

I have dynamically loaded(based on search result) content. (see the following)
(stackoverflow is not allowing me to embed the image as I am still new)
https://i.imgur.com/WVVc0wM.png

Code for the above;

     echo '
    <td><a href="profile/?student='.$row['sid'].'">'.$row['use_name'].'</a></td>
    <td>'.$row['admission_number'].'</td>
    <td>'.$row['dob'].'</td><td>Not Assigned</td>
    <td>
<form>
<input type="hidden" name="sid" class="sid" value="'.$row['sid'].'">
<input type="hidden" name="classID" class="classID" value="1">
<button class="btn btn-warning btn-sm add" type="button" name="add"><i class="fas fa-pencil-alt"></i> Add</button>
</form>
</td>
<td>
    <div id="res"></div>
</td></tr>';
                        }

I want to pass sid, classID to a seperate php file called add-student.php

$(".add").click(function() { 
    $.ajax({
           type: "POST",
           url: "add-student.php",
        data:'sid='+$(".sid").val()+'&cid='+$(".classID").val(),
           success: function(data) {
               alert(data); 
           }
    });
    return false; 
});
</script>

The following is add-student.php

<?php
    require('../../dbc/dbconn.php');
    $student = $_POST['sid'];
    $class = $_POST['cid'];
    $user = "System";
    
    //check the existance
    $check = mysqli_query($condb, "select sid, cid from studentsclasses where sid = '$student' and cid = '$class'");
    if(mysqli_num_rows($check)>0){
        echo 'The record already exists';
    }
    else{
        $insert = mysqli_query($condb, "insert into studentsclasses (sid, cid, createdBy) value('$student', '$class', '$user')");
            if($insert){
                echo 'Success';
            }
            else{
                echo 'Error';
            }   
    }
?>

When I click ‘Add’ button for first time, it successfully adds to the database.
But when I click ‘Add’ button in a different row, I am getting The record already exists error.
Please give your advises.

Advertisement

Answer

Add the required data to pass on the element directly via data-attributes for $(".sid").val() will only ever get you the value of the first element based on the html you supplied.

When the first value is always the one being passed, it is expected that your checks on your backend will notify you that the record already existed.

You can change your markup to this:

<button class="add" type="button" name="add" data-sid="'.$row['sid'].'" data-cid="1">Add</button>

Then listen on the click event and send the ajax

$(function(){
    $('.add').on('click', function(){
        const sidval = $(this).data('sid')
        const cidval = $(this).data('cid')
        $.ajax({
           type: "POST",
           url: "add-student.php",
           data: {
              sid: sidval,
              cid: cidval
           },
           success: function(data) {
               alert(data); 
           }
        });
    })
})

https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement