Search code examples
phpjqueryajaxdelete-rowsql-delete

jQuery ajax delete script not actually deleting


I have a little personal webapp that I'm working on. I have a link that, when clicked, is supposed to make an ajax call to a php that is supposed to delete that info from a database. For some unknown reason, it won't actually delete the row from the database. I've tried everything I know, but still nothing. I'm sure it's something incredibly easy... Here are the scripts involved.

Database output:

 $sql = "SELECT * FROM bookmark_app";
    foreach ($dbh->query($sql) as $row)
 {
 echo '<div class="box" id="',$row['id'],'"><img src="images/avatar.jpg" width="75" height="75" border="0" class="avatar"/>
     <div class="text"><a href="',$row['url'],'">',$row['title'],'</a><br/>
     </div>
            /*** Click to delete ***/
     <a href="?delete=',$row['id'],'" class="delete">x</a></div>
  <div class="clear"></div>';
        }

    $dbh = null;

Ajax script:

$(document).ready(function() {
$("a.delete").click(function(){

 var element = $(this);

 var noteid = element.attr("id");

 var info = 'id=' + noteid;

  $.ajax({
    type: "GET",
    url: "includes/delete.php",
    data: info,
    success: function(){
    element.parent().eq(0).fadeOut("slow");
    }
  });
 return false;
 });
});

Delete code:

include('connect.php');

//delete.php?id=IdOfPost
if($_GET['id']){

$id = $_GET['id'];

//Delete the record of the post
$delete = mysql_query("DELETE FROM `db` WHERE `id` = '$id'");

//Redirect the user
header("Location:xxxx.php");

}

Solution

  • Ah just spotted your error, in the href you're generating you're not setting the id attribute. It should be something like:

    <a href="..." id="'. $row['id'] . '" class="delete">x</a>
    

    Of course that's just an immediate example, you must escape these kinds of things but this should let you access the item in jQuery.