views:

216

answers:

2

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");

}
+3  A: 

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.

Alistair
Don't forget that 'destructive' requests should be done via POST as otherwise simply browsing to the 'wrong' URL can cause records to be deleted.
Alistair
Well, it worked... until I moved it to my web server. Now FireBug is telling me "Warning: mysql_query() [function.mysql-query]: Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) in xxxx/includes/delete.php on line 20.Stupid Media Temple.
werm
Perhaps http://kb.mediatemple.net/questions/4/Why+can%27t+I+connect+to+my+MySQL+database+from+PHP%3F might help you get connected? They have some code samples depending on how you're setup.
Alistair
A: 

You may want to modify your delete script to not just redirect after the DB query. Since it's being called via AJAX, have it at least return a success/error code to the javascript:

// can't return $delete unconditionally, since *_query() returns an object
if ($delete) { 
   return(json_encode(array('code' => 1, 'msg' => 'Delete succeeded')));
} else {
   return(json_encode(array('code' => 0, 'msg' => 'Delete failed: ' . mysql_error()));
}

It's bad practice to assume a database call succeeded.

Marc B