php 使用jquery ajax删除表中的记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15917833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:11:44  来源:igfitidea点击:

delete record in a table using jquery ajax

phpjquerypartial-page-refresh

提问by chithon

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

我正在学习 j 查询 Ajax 事件。我已经使用 j 查询 Ajax 在 php 中插入并显示了记录,但我无法删除记录我已经编写了代码但它不起作用,我不想再次加载表。请帮忙

TableName : login

表名:登录

Column: id,username,message

列:id、用户名、消息

comment.php

评论.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

  <?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

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

  }

?>

回答by Shwet

in your delete.php page there is little bug.

在您的 delete.php 页面中,有一些小错误。

    $(".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 idin url and get midso change your delet.phpaccpording to this.

您传入idurl 并根据此mid更改您的delet.php内容。

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

  }

?>

回答by Gaurang P

enter image description here

enter image description here

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

这是使用 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.

这是 JQuery 的函数,它在文档准备好后立即运行。这类似于 onload 事件,但 JQuery 的功能远比这快得多。所以我们希望能够在页面准备好时运行这段代码。

$('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.

如果您曾研究过 CSS 选择器,那么上面的行对您来说应该不会太神秘。您可以使用相同的语法使用 JQuery 来定位元素。基本上,它表示其中带有 id delTable 和 TD 的表在单击时具有类删除的超链接,运行此函数中指定的代码。因此,当单击 id 为 delTable 的表中 TD 中名为 delete 的类的超链接时,将执行指定的代码。

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.

请记住,在 JQuery 中,$(this) 始终指代目标元素,在我们的例子中是带有类删除的超链接。attr 用于获取或设置标签的属性。所以 id 变量指的是这个超链接的父级,即 TD,然后是这个 TD 的父级,即 TR。所以这里我们得到了这个TR的id属性。在 HTML 代码中,我们将每一行的主键字段分配给这些 TR,以识别和删除记录。data 变量使数据作为使用 JQuery 发出的 ajax 请求的一部分发送。父变量是指包含目标元素的每个TR,该元素与类删除超链接。

$.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.

$.ajax 函数用于发送ajax 请求。在它的参数中,类型是指请求的方法,无论是 POST 还是 GET,url 是指将获取 ajax 请求数据并返回一些响应的脚本,数据是指作为 ajax 请求的一部分发送的数据,类似于查询字符串表单,缓存控制请求的缓存是打开还是关闭,因为在 IE 中请求被缓存,如果请求成功,成功函数也是 $.ajax 函数的属性,它会运行其中的代码。

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.

正如之前所解释的,在我们的案例中,parent 指的是 TR。淡出函数需要两个参数;动画速度和要执行的功能。所以这条线的作用是它通过淡出它来删除父链接,然后使用 remove() 方法删除目标链接。这样整行都消失了,在ajax请求的帮助下,数据库中的记录也被删除了。这里我们使用了JQuery的fadeOut动画功能,但是还有更多的动画可用。

$('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.

此行表示将背景样式应用于具有 id delTable 的表的每个奇数 TR。现在因为我们的代码在页面准备好时执行,因此我们的表格将为每个奇数行提供不同的颜色。

You can download it here.

你可以在这里下载。

回答by chandresh_cool

in javascript change

在 javascript 中更改

var dataString = 'id='+ id ; 

to

var dataString = 'mid='+ id ; 

回答by Nikola R.

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

我会这样做,更简单,更干净:

delete.php

删除.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:

js脚本:

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.

我的“var row”在您的代码中是“var parent”,我只是使用了不同的元素名称和 ID。你应该用你的。

Instead of Cheers!

而不是干杯!

回答by Arun P Johny

I'm seeing two problems here

我在这里看到两个问题

  1. The server side variable is called midwhere you are sending id
  2. The parentneed to point to trin 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;
    

    });

  1. 服务器端变量mid在你发送的地方被调用id
  2. parent需要指向tr你的情况下,它是指向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;
    

    });

回答by Edwin Alex

I think the the problem is in the variable name.

我认为问题出在变量名上。

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

在您的 AJAX 函数中,您使用了变量 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']

但是在删除过程中,你是从 $_POST['mid']

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

回答by Vijay Joseph

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

$id = $_POST['id']delete.php 中使用而不是$_POST['mid'],那么它应该可以工作。

回答by Ranjith

POST valuesare different. change delete.php POST valueslike this.

POST values是不同的。delete.php POST values像这样改变。

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

  }

?>

回答by hijarian

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

伙计,您的 javascript 代码中有以下行,在删除处理程序中:

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

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

因此,您从删除链接中获取了一个不存在的 'mid' 属性。

In your process.php:

在您的process.php

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

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

您显然应该.attr('id')id变量分配一个。

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

此外,正如其他评论者所指出的,您的delete.php脚本需要一个$_POST['mid']参数,但您向id它发送了一个参数。

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

为什么会有奇怪的命名?只需放下这个“中间”的东西并在任何地方使用“id”。

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 hrefattribute of this link, in your case - scrolling page up to top.

顺便说一句,如果您为 HTML 链接分配自定义点击处理程序,最好event.preventDefault()在处理程序中作为第一件事调用,否则浏览器将尝试遵循href此链接的属性,在您的情况下 - 将页面滚动到顶部.