delete record in a table using jquery ajax [closed

2019-03-21 16:12发布

问题:

I am learning j query Ajax events.I have inserted and displayed records in php using j query Ajax but I am not able to delete record I have written code but its not working and I don't want table to load again.Please help

TableName : login

Column: id,username,message

comment.php

    <script type="text/javascript">
$(document).ready(function(e) {
 function showComment(){
     $.ajax({
     type:"post",
      url:"process2.php",
      data:"action=showcomment",
      success:function(data){
       $("#flash").html(data);
      }
    });
   }
showComment(); 

//Insert records 
$("#Submit").click(function(){

            if($(":text").val().length==0)
            {
               // $(this).next().html("Field needs filling");
               $(":text").after('<span class="errorkeyup">Field cannot be empty</span>');
                //return false;
                success = false;
            }
            else
            {
                var name=$("#name").val();
                var message=$("#message").val();
                $.ajax({
                  type:"post",
                   url:"process2.php",
                   data:"name="+name+"&message="+message+"&action=addcomment",                            
                  success:function(data){
                  showComment();                                  
                 } 
                }); 
            }

  });

$('.delete').click(function(e){
    e.stopPropagation();
            var deleteID = $(this).attr('name');
            var row = deleteID;
            $.ajax({
                type: "POST",
                url: "delete.php?deleteID=" + deleteID,
                data: "deleteID="+ deleteID,
                success: function(result){
                    $('#row'+row).fadeOut('fast');
                }
            });

        });     
});



</script>
    </head>

    <body>
    <form method="post" name="form" action="">
<div id="content">
 Name :    <input type="text" name="name" id="name"/>
               </br>
               Message : <input type="text" name="message" id="message" />
               </br>
               </div>
<input type="button" value="Submit" id="Submit">
</form>
</div>
<div id="flash"></div>

            </form>
    </body>

process.php

  <?php
  mysql_connect("localhost","root","dot1235");
  mysql_select_db("chitra");


  $action=$_POST["action"];

  if($action=="showcomment"){
     $show=mysql_query("Select * from login order by id ASC");
 echo "<table border=1 id=t1>";

   echo "<tr>";
   echo "<td>SrNo.</td>";
   echo "<td>Name</td>";
   echo "<td>Message</td>";
   echo "<td>Delete</td>";   
   echo "</tr>";
   $i=1;
     while($row=mysql_fetch_array($show)){
        //echo "<li><b>$row[name]</b> : $row[message]</li>";
        echo "<tr>";
    echo"<td>".$i."</td>";
    echo "<td>" .$row['username'] ."</td>"; 
    echo "<td>" .$row['message'] ."</td>";
    echo "<td><a href='javascript:void(0)'><img src=delete.png class=delete name=".$row[id]."</a></td>" ;
    echo "</tr>";
    $i++;
     }
     echo"</table>";
  }
  else if($action=="addcomment"){
    $name=$_POST["name"];
    $message=$_POST["message"];

     $query=mysql_query("insert into login(username,message) values('$name','$message') ");

     if($query){
        echo "Your comment has been sent";
     }
     else{
        echo "Error in sending your comment";
     }
  }


?>

delete.php

<?php
include("connection.php");
 if(isset($_POST['id']))
  {
   $id = $_POST['id'];
   $id = mysql_escape_String($id);
   $delquery=mysql_query("delete from login where id=$id") or die(mysql_error());
   //echo "Record deleted";

  }

?>

回答1:

in your delete.php page there is little bug.

    $(".delete_button").click(function() {
var id = $(this).attr("mid");
var dataString = 'id='+ id ;
var parent = $(this).parent();

$.ajax({
   type: "POST",
   url: "delete.php",
   data: dataString,
   cache: false,

   success: function()
   {
    if(id % 2)
    {
    parent.fadeOut('slow', function() {$(this).remove();});
    }
    else
    {
    parent.slideUp('slow', function() {$(this).remove();});
    }
  }

you pass id in url and get mid so change your delet.php accpording to this.

<?php
include("connection.php");
 if(isset($_POST['id']))  //mid to id
  {
   $id = $_POST['id']; //mid to id
   $id = mysql_escape_String($id);
   $delquery=mysql_query("delete from login where mid=$id") or die(mysql_error());
   //echo "Record deleted";

  }

?>


回答2:

Here is the heart of the entire logic coded with JQuery:

$(document).ready(function()
{
    $('table#delTable td a.delete').click(function()
    {
        if (confirm("Are you sure you want to delete this row?"))
        {
            var id = $(this).parent().parent().attr('id');
            var data = 'id=' + id ;
            var parent = $(this).parent().parent();

            $.ajax(
            {
                   type: "POST",
                   url: "delete_row.php",
                   data: data,
                   cache: false,

                   success: function()
                   {
                    parent.fadeOut('slow', function() {$(this).remove();});
                   }
             });
        }
    });

    // style the table with alternate colors
    // sets specified color for every odd row
    $('table#delTable tr:odd').css('background',' #FFFFFF');
});

Let’s find out what’s happening here using divide and rule methodology.

$(document).ready(function()

This is JQuery’s function which runs as soon as document becomes ready. This is similar to onload event but JQuery’s function is far more faster than that. So we want to be able to run this code when page is ready.

$('table#delTable td a.delete').click(function()

If you have worked on CSS selectors then above line should not be much of mystery to you. You can use the same syntax to target elements using JQuery. Basically it says that table with id delTable and TD inside it that has hyperlink with class delete when clicked runs the code specified within this function. So when hyperlink with class named delete within TD within table with id delTable is clicked then code specified will execute.

if (confirm("Are you sure you want to delete this row?"))

We want to be able to confirm if user really wants to delete a row.

var id = $(this).parent().parent().attr('id');
var data = 'id=' + id ;
var parent = $(this).parent().parent();

Please keep in mind that in JQuery, the $(this) always refers to the target element which in our case is hyperlink with class delete. attr is used to get or set attributes of the tags. So the id variable refers to the parent of this hyperlink which is TD and then this TD’s parent which is TR. So here we get the id attribute of this TR. In HTML code, we will assign each row’s primary key field to these TRs to identify and delete records. The data variable makes data to be sent as part of the ajax request made using JQuery. The parent variable refers to each TR containing the target element which is hyperlink with class delete.

$.ajax(
{
       type: "POST",
       url: "delete_row.php",
       data: data,
       cache: false,

       success: function()
       {
        parent.fadeOut('slow', function() {$(this).remove();});
       }
 });

The $.ajax function is used to send ajax requests. Amongst its arguments, the type refers to method of request whether it POST or GET, url refers to script which will get the ajax request data and return some response, data refers to data to be sent as part of the ajax request similar to query string form, cache controls whether cache will be on or off for the request because in IE requests are cached and success function which is also attribute of the $.ajax function runs the code inside it if the request went successful.

parent.fadeOut('slow', function() {$(this).remove();});

As explained before parent refers to the TRs in our case. fadeOut function needs two arguments; animation speed and function to execute. So what this line does is that it removes parent by fading it out and then the target link by using the remove() method. In this way entire row is gone and with the help of ajax request, the record from database is also deleted. Here we have used the fadeOut animation function of JQuery but there are more animations available.

$('table#delTable tr:odd').css('background',' #FFFFFF');

This line means that apply background style to each odd TR of the table with id delTable. Now because our code executes when page is ready, therefore our table will have alternate colors for each odd row.

You can download it here.



回答3:

in javascript change

var dataString = 'id='+ id ; 

to

var dataString = 'mid='+ id ; 


回答4:

POST values are different. change delete.php POST values like this.

<?php
include("connection.php");
 if(isset($_POST['id']))   // changed into 'id'
  {
   $id = $_POST['mid'];
   $id = mysql_escape_String($id);
   $delquery=mysql_query("delete from login where mid=$id") or die(mysql_error());
   //echo "Record deleted";

  }

?>


回答5:

Man, you have the following line in your javascript code, in delete handler:

var id = $(this).attr("mid");

So, you grab a nonexistent 'mid' attribute from your Delete link.

In your process.php:

<td><a href="#" id="<?php echo $mid; ?>" class="delete_button">Delete</a></td>

You clearly should assign an .attr('id') to the id variable.

Also, as was pointed out by other commenters, your delete.php script expects a $_POST['mid'] parameter, but you send an id to it.

Why the strange naming at all? Just drop this "mid" stuff and use the "id" everywhere.

And by the way, if you assign a custom click handler to a HTML link, it's better to call event.preventDefault() as a first thing in handler, because otherwise browser will try to follow the href attribute of this link, in your case - scrolling page up to top.



回答6:

I'm seeing two problems here

  1. The server side variable is called mid where you are sending id
  2. The parent need to point to tr in your case it is pointing to td

    $(".delete_button").click(function() { var id = $(this).attr("mid"); var dataString = 'mid=' + id; var parent = $(this).closest('tr');

    $.ajax({
                type : "POST",
                url : "delete.php",
                data : dataString,
                cache : false,
    
                success : function() {
                    if (id % 2) {
                        parent.fadeOut('slow', function() {
                                    $(this).remove();
                                });
                    } else {
                        parent.slideUp('slow', function() {
                                    $(this).remove();
                                });
                    }
                }
    
            });
    
    return false;
    

    });



回答7:

I think the the problem is in the variable name.

In your AJAX function, you have used variable name 'id'.

$(".delete_button").click(function() {
  var id = $(this).attr("mid");
  var dataString = 'id='+ id ; // Here
  var parent = $(this).parent();

But in the delete process, you are getting it from $_POST['mid']

if(isset($_POST['mid'])) // Change this to $_POST['id']
  {
    $id = $_POST['mid']; // Change this to $_POST['id']


回答8:

Use $id = $_POST['id'] in delete.php instead of $_POST['mid'], then it should work.



回答9:

I would do it like this, much simpler and cleaner:

delete.php

<?php

include("connection.php");
if(!isset($_REQUEST['action'])) die("Invalid request");
if(!isset($_REQUEST['id'])) die("Invalid Comment ID");
$action = $_REQUEST['action'];
if($action == 'remove_comment') {
    $id = (int)$_REQUEST['id'];
    $delquery = mysql_query("DELETE FROM `login` WHERE mid=$id") or die(mysql_error());
    echo 1;
}
?>

js script:

function RemoveComment(comment_id) {
    var row = $("table#comments tr#commentid-"+comment_id);
    if(row.length < 1) return false; //if element doesnt exist on our page
    $.post("http://yourhost/delete.php", { action: "remove_comment", id: comment_id },
    function(response) {
        if(response == 1) row.fadeOut();
        else alert(response);
    });
}

EDIT:

$(".delete_button").click(function() {
var id = $(this).attr("id");
var dataString = 'id='+ id ;
var parent = $(this).parent();

my "var row" is "var parent" in your code, I just used different element names and IDs. You should use yours.

Instead of Cheers!