简体   繁体   中英

Fetching td value in php file and sending back

I'm facing an issue to get the value of td when a link is clicked

search_code.php

echo "<table class='table table-hover'>";
echo "<tr><th>Institute ID</th><th>Institute Name</th><th>State</th><th>District</th><th>City</th><th>General Seats</th><th>Reserved Seats</th></tr>";

// output data of each row
while($row = $result->fetch_assoc()) {
    echo "<tr><td id='instid'>".$row["collegeUniqueId"]."</td><td id='instname'><a href='#' onClick='getCourses(".$row["collegeUniqueId"].");'>".$row["name"]."</a></td><td>".$row["state"]."</td><td>".$row["district"]."</td><td>".$row["city"]."</td><td>".$row["openSeat"]."</td><td>".$row["reservedSeat"]."</td></tr>";
}

echo "</table>";

and in search.php

<script>
    $(document).ready(function(){
        $('#search').click(function(e){
            e.preventDefault();
            $.ajax({
                type: 'POST',
                url: 'search_code.php?state=' + $('#state').val() + '&district=' + $('#district').val(),
                success: function(institute){
                    $('#institute').html(institute);
                }
            });
        });

        function getCourses(id) {
            $id = id;
            $.ajax({
                type: 'POST',
                url: 'courses.php?courseid=' + id,
                success: function(courses){
                    $('#courses').html(courses);
                }
            });
        }
    });
</script>

You haven't shown the HTML that gets produced, but if the "ID" value is anything other than a number , you need to put it in quotes:

echo "...onClick='getCourses(\"".$row["collegeUniqueId"]."\");'>...";
// --------------------------^^---------------------------^^

Side note: You'll also want to deal with those repeated id values the loop creates (assuming there's ever more than one row in the result set).


Side note 2: You're falling prey to The Horror of Implicit Globals in your getCourses function: You never declare the $id variable. You can just remove it, you're not using it for anything.

ID in HTML needs to be unique you can't have multiple elements with same ID.

There are at least 2 ways to fix it:

  1. Use class attribute and use data-id attribute to get ID of particular row
  2. In your PHP you can generate id with ROW id <td id='instid-".$row["collegeUniqueId"]."'>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM