Sidhant Kushwaha Sidhant Kushwaha - 4 months ago 19
Ajax Question

How to access the textbox value created inside php tag to the ajax call

I am unable to access the textbox value which i created inside the the php tag to the ajax call. When i am printing the textbox value in ajax call its 'undefined', so is there any way to accesss the textbox value. See the comment in the code at line 39.



<html>
<?php
include 'config.php';
include 'dbconnect.php';
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<table border="1">
<tr>
<th>categoryId</th>
<th>category</th>
<th>Operations</th>
</tr>
<?php
$sql_query = "select category_id,category from cart_category_descriptions limit 10;";
$result = $conn->query($sql_query);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<tr id='.$row["category_id"].'><td>'.$row["category_id"].'</td><td><input type=text name="cat" value='.$row["category"].'></td><td><button class="deletedata">Delete</button><button class="updatedata">Update</button></td></tr>';
}
}
else {
echo "0 results";
}
?>
<script>
$(document).on('click','.deletedata',function(){
id = $(this).closest('tr').attr('id'); // Get the clicked id for deletion
alert(id);
$.ajax({
type:'POST',
url:'delete.php',
data:{delete_id:id},
success:function(data){
window.location.reload();
}
})});
$(document).on('click','.updatedata',function(){
id = $(this).closest('tr').attr('id');// Get the clicked id for deletion
alert($("#cat").val());// cannot access, undefined
$.ajax({
type:'POST',
url:'update.php',
data:{update_id:id,
cat: $("#cat").val()},
success:function(data){
alert("updated");
}
})});
</script>
</table>
</html>




Answer

You are trying to access input boc value by id this is issue because id not mentioned in input attribute.

$(document).on('click','.updatedata',function(){
            id = $(this).closest('tr').attr('id');// Get the clicked id for deletion
            cat_val=$(this).closest('tr').find('input[name="cat"]').val();
            $.ajax({
                type:'POST',
                url:'update.php',
                data:{update_id:id,
                      cat: cat_val},
                success:function(data){
                    alert("updated");
                }
            })});