User_coder
User_coder

Reputation: 516

Delete record with ajax via id

Having trouble deleting a record from mysql databse using ajax/jquery. Issue I am having is that it does not delete from the database but does delete from the list. What am I doing wrong here?

Here is my code:

jQuery(document).ready(function(){
  $(".deleteitem").click(function(){

    var parent = $(this).closest('li');
    var id = parent.attr('id');

    $.ajax({
      type: "POST",
      data: "id=" +id,
      URL: "delete.php",
      success: function(msg){
        $('#'+id).remove();
      }
    });
  });
});

My php file delete.php:

$con=mysqli_connect("localhost","user","pass","db");
// Check connection
if (mysqli_connect_errno())
{ echo "Failed to connect to MySQL: " . mysqli_connect_error(); }

$id = $_POST['id'];

if (isset($id)) {
  $query = "DELETE FROM img_slider WHERE id = '$id'";
  mysqli_query($query) or die('Error, insert query failed');
}

The HTML markup:

<li id='".$row['id']."'>
<a href='#' class='deleteitem'><img src='../img/delete.png'></a>
</li>

Upvotes: 0

Views: 3473

Answers (1)

elzaer
elzaer

Reputation: 729

Firstly test to make sure calling the delete file with a valid id works. The javascript below should work fine.

<script type="text/javascript">
<!--
$(function() {
  $('.deleteitem').click(function(e) {
    e.preventDefault();
    var id = $(this).parent('li').attr('id');
    $.get('delete.php',{ id: id}).done(function(data) {
      if(data=='Error, insert query failed') {
          // dont delete from list
          alert('Failed to delete '+id);
      } else {
          //delete from list
          $('#'+id).remove();
          alert('Deleted '+id);
      }
    });
  });
});
//-->
</script>

EDIT: updated the script to assist parent-id handling.

Are you able to say where the error is coming from? Most modern browsers should offer you some insight into what line, or what section the error is occurring on.

The script above should replace all your javascript.

Upvotes: 2

Related Questions