-1

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.stack.imgur.com/n7KoE.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.

  • 1
    First of all, you should fix your HTML - that is massively faulty, in multiple regards. You can not nest a form into a table like that - the form either has to go around the complete table, or be contained in a single table cell. And you can not nest _interactive_ elements such as `a` and `input`/`button` into each other, that is also not allowed by the rules of HTML. (Why would you wrap those into a link here in the first place, what sense is that even supposed to make?) – CBroe May 27 '21 at 07:22
  • `$(".sid").val()` will only ever get you the value of the _first_ element in that selection. You need to find a way to limit the “context” of this selection, so that you find the _proper_ input fields, that are related to the “add” button you actually clicked. – CBroe May 27 '21 at 07:25
  • @CBroe - I just wanted to link the profile. Anyway, I have corrected errors. – Shane Perera May 27 '21 at 07:28
  • @CBroe - I am pretty new to ajax. Kindly help me to resolve this. – Shane Perera May 27 '21 at 07:29
  • This should be set up as an object `data:'sid='+$(".sid").val()+'&cid='+$(".classID").val(),` should be `data:{sid:$(".sid").val(), cid: $(".classID").val()}` – Kinglish May 27 '21 at 07:30
  • You can f.e. navigate from the clicked button up to the parent form element (`.parent()`), and then `find` the input elements by class below that. – CBroe May 27 '21 at 07:32
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman May 27 '21 at 10:07

1 Answers1

0

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

jpneey
  • 620
  • 1
  • 9
  • 16