user3079187
user3079187

Reputation: 3

Jquery function not work with php echoing code

I'm new to php.
I want to use jquery to delete a table row from php echoing code, but it doesn't work. Here is my html code:

<!DOCTYPE html>
<html>
<head>
<title>test insert</title>
<script src="jquery-2.0.3.js"></script> 
<script type="text/javascript">
$(document).ready(function(){
    $('.del').click(function(){
        $(this).parent().parent().fadeOut('slow');
    });

    $('#show').click(function(){
        $.post('data.php',{action: "show"},function(res){       
            $('#result').hide().html(res).fadeIn('slow');   
        });     
    });
});
</script>
</head>
<body>
   <h2>Show Data</h2>
   <button id="show">Show</button>
   <p>Result:</p>
   <div id="result"></div><br>
</body>
</html>

and here is my php code:

<?php
//connect to db
$con = mysql_connect('localhost','root');
$db = mysql_select_db('test');
//if show key is pressed show records
if($_POST['action'] == 'show'){
    $sql   = "select * from customer order by Firstname";
    $query = mysql_query($sql);

    echo "<table><tr><th>Firstname</th><th>Lastname</th><th>Keynumber</th>
    <th>Number2</th><th>Number3</th><th>Option</th><th><button class='del' >delete</button></th></tr>";
    while($row = mysql_fetch_array($query)){
        echo "<tr><td>$row[firstname]</td><td>$row[lastname]</td><td class='key'>$row[keynumber]</td>
        <td>$row[number2]</td><td>$row[number3]</td><td><button class='del' >delete</button></td></tr>";
    }
    echo "</table>";
}
?>

When I press the 'delete' button, it doesn't work.
I don't know why it doesn't work:(

Upvotes: 0

Views: 126

Answers (2)

Ashish Jain
Ashish Jain

Reputation: 770

I have corrected ur code just check it,

<script type="text/javascript">
$(document).ready(function(){
    $('.del').click(function(){
        $(this).parent().parent().fadeOut('slow');
    });

    $('#show').click(function(){
        $.post(
         url:'data.php',
         data:{action: "show"},
         type:'POST',
         function(res){       
            $('#result').hide().html(res).fadeIn('slow');   
        });     
    });
});

</script>

Upvotes: 0

j08691
j08691

Reputation: 207861

It looks like your data is loaded dynamically when the show button is clicked. If so, you need to use .on() instead of .click(), and .on()'s delegated event syntax. Change your delete button code to:

$(document).on('click', '.del', function(){
    $(this).parent().parent().fadeOut('slow');
});

Upvotes: 1

Related Questions