0

I'm trying to create a HTML table that lists all the rows in a database table. Then, next to each row I want to have a button so the user can delete that entry. I have created the table but I can't get the buttons to work.

I have been searching around and I found this post How to Call a PHP Function on the Click of a Button but I can't get it to work. I've never used ajax before so I might not understand the code correctly.

Here is the code:

Go through all the data from the table and create a button for each entry

<?php
for ($x = 0; $x < sizeof($data); $x++) {
?>
     <input type="submit" class="tableButton" name="<?php echo $x ?>" value="<?php echo $x ?>">
<?php
}    
?>

When a tableButton is clicked, send its value to ajax.php

$('.tableButton').click(function () {
    var clickBtnValue = $(this).val();
    var ajaxurl = 'ajax.php',
    data = { 'action': clickBtnValue };
    $.post(ajaxurl, data, function (response) {
    });
});

ajax.php

Get the value of the button that was pressed and do something with it

<?php
if (isset($_POST['action'])) {
    $data = $_POST['action'];
    echo $data;
}
?>

Currently I just have it echo the value to test it but it's displaying nothing. What I would have it do is run this query:

 DELETE from myTable WHERE id = $data;

Or if someone knows a better way to do this please let me know.

Edit

After doing a lot more searching I found out why this wasn't working how I expected. As I suspected since I've never used AJAX before there was something I missed, I didn't know the echo wouldn't print directly to the screen. I just changed the echo to a delete query and tested that and it works... So the code is fine, but I think I should learn AJAX sometime. Thanks for all the responses.

I'm also aware of the sql injection that is possible here, this was just a quick mock-up, thanks.

Community
  • 1
  • 1
user1009573
  • 113
  • 2
  • 13
  • That's a nice SQL injection vulnerability. –  Jul 03 '14 at 13:22
  • @André: credit where it's due: at least OP knows about `isset`... to the OP: what if users changed the value of your button to _"%"_, using that value in your query gives: `DELETE FROM myTable WHERE id = "%"`, that's not what you'd call secure, is it? – Elias Van Ootegem Jul 03 '14 at 13:26
  • Here : [How can I prevent SQL-injection in PHP?](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) with a nice example of an injection-proof prepared statement, you can almost copy/paste that in your PHP code instead of the `echo $data` and adjust the query. –  Jul 03 '14 at 13:30
  • 1
    Your code as it given shouldn't display anything because you do nothing with `response` of post request – hindmost Jul 03 '14 at 13:33

3 Answers3

1

It is hard to help you from this point of view we got.

You should do some debugging, like:

  1. Check if the associated ajax.php is called (by checking the console with "F12" for example)
  2. If yes, check the data being passed through your ajax POST
  3. If not, maybe the reference link is wrong

Let me hear what you got.

Thomas
  • 11
  • 2
  • In this case the Javascript/AJAX part looks fine, it's just that the author doesn't know what to do on the PHP part, so your answer is irrelevant. –  Jul 03 '14 at 13:33
  • You are the second guy flaming, meh I thought this community was about to be constructive. Instead of wasting the time with that statement, better help him. The PHP part looks alright as well btw. Greetz – Thomas Jul 03 '14 at 13:35
  • I wasn't flaming, I was just telling you that your answer is irrelevant so you can improve it/delete it/whatever before someone comes it and actually flames or downvotes you. And I'm not sure how the PHP part can look alright if there's no database query in there. –  Jul 03 '14 at 13:39
  • Right, we are running nowhere with this. Read the question again, the PHP part is right, in this example he's just trying to display anything, as he wrotes as well. I guess the correct answer to question was given by "hindmost" on the top. Greetz – Thomas Jul 03 '14 at 13:42
1

Ok. First of all you need to create the button with row id. You can do it using mySQL and PHP loops. Create it in this following format.

<input type="submit" name="test" data-id="23" value="Remove" class="delete_row" />            
<input type="submit" name="test" data-id="24" value="Remove" class="delete_row" />            
<input type="submit" name="test" data-id="25" value="Remove" class="delete_row" />            
<input type="submit" name="test" data-id="26" value="Remove" class="delete_row" />  

Here replace the data-id in each button with the id of row you are looking to delete.( Replace 23,24 etc with database ids dynamically ).

Java script

$(document).ready(function(){

    $(".delete_row").click(function(e){

        e.preventDefault();
        var deleteId = $(this).attr("data-id");//unique id of the raw to be deleted

        var request = $.ajax({
        url: "ajax.php",
        type: "POST",
        data: { id : deleteId },
        dataType: "json"
        });
        request.done(function( msg ) {

           if( msg.status )
               alert("Deleted successfully!");
           else
               alert("Something gone wrong!!");
        });
        request.fail(function( jqXHR, textStatus ) {
           alert( "Request failed: " + textStatus );


        });

    });


});

ajax.php

<?php
   /* AJAX check  */
   if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {

       $delete_id = $_POST["id"];
       if( is_numeric( $delete_id ) ){

            /*DELETE QUERT WHERE id = $delete_id (Try to use mysqli or PDO ) */
            /* $affected_rows = effected_rows() */

            if( $affected > 0 ) 
            {
                echo json_encode( array("status" => true ) );die;
            }

        }
        echo json_encode( array("status" => false ) );die;
     }
     die("Get out of here!");
?>

I hope this will help you :)

Mijoe
  • 236
  • 2
  • 9
1

You can try by this way. I think it will help you

Html File

<html>
<head>
<title>Test</title>
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
$('.tableButton').live('click', function(){
    var id = $(this).val();
    $.ajax({
        url:'ajax.php'
        ,data:{id:id}
        ,type:'post'
        ,success:function(data){
            if(data == 'success'){
                $('#' + id).remove();
            }
        }
    });
});
</script>
<?php
  for ($x = 0; $x < 5; $x++) {
?>
<input type="submit" class="tableButton" id="<?=$x?>" name="<?php echo $x ?>"value="<?php echo $x ?>">
<?php
 }
 ?>
 </body>
 </html>

ajax.php

<?php
if(isset($_POST['id'])){
    $id = $_POST['id'];
    //delete operation here
    //if(deleted) echo 'success';
}
?>
MH2K9
  • 11,951
  • 7
  • 32
  • 49