使用Jquery和Ajax删除表的多行

时间:2018-12-13 08:33:06

标签: javascript jquery ajax

我希望能够删除复选框选择的行,但是当我单击“删除选定的内容”时,网页上的表和MySQL数据库均保持不变。如何从网页和数据库中获取要删除的行?

编辑:尽管选择了多个复选框,或者选择不在第一行的另一个复选框,我现在仍可以删除行,但仅删除第一行。另外,如果要删除其他条目,则必须先刷新页面,然后再删除另一个条目。

datatable.php

<div class="row well">
    <a type="button" class="delete_all btn btn-primary pull-right">Delete Selected</a>
</div>

<script type="text/javascript">

$(document).ready(function($)
{

function create_html_table (tbl_data) {

tbl +='<table>';
tbl +='<thead>';
tbl +='<tr>';

tbl +='<th rowspan="3"><input type="checkbox" id="master"></th>';
// More table headers
tbl +='</tr>';
tbl +='</thead>';

tbl +='<tbody>';

          $.each(tbl_data, function(index, val) 
            {   
                var row_id = val['row_id'];

                //loop through ajax row data
                tbl +='<tr id="row" row_id="'+row_id+'">';

                    tbl +='<td><input type="checkbox" class="sub_chk"></td>';
                    tbl +='<td>'+(index + 1)+'</td>';
                    tbl +='<td><div col_name="filename">'+val['filename']+'</div></td>';
                    // More data
                tbl +='</tr>';
             });

tbl +='</tbody>';
tbl +='</table>';
}

var ajax_url = "<?php echo APPURL;?>/ajax.php" ;

// Multi-select
$(document).on("click","#master", function(e) {

if($(this).is(':checked',true))  
{
    $(".sub_chk").prop('checked', true);  
}  
else  
{  
    $(".sub_chk").prop('checked',false);  
}  
});

//Delete selected rows
$(document).on('click', '.delete_all', function(event) 
{
    event.preventDefault();

    var ele_this = $('#row') ;
    var row_id = ele_this.attr('row_id');

    var allVals = [];
    $(".sub_chk:checked").each(function()
    {    
    allVals.push(row_id);
    });

    if(allVals.length <=0)  
    {  
        alert("Please select row.");  
    }

    else {

    var data_obj=
    {
        call_type:'delete_row_entry',
        row_id:row_id,
    };  

    ele_this.html('<p class="bg-warning">Please wait....deleting your entry</p>')

    $.post(ajax_url, data_obj, function(data) 
    { 
        var d1 = JSON.parse(data); 
        if(d1.status == "error")
        {
            var msg = ''
            + '<h3>There was an error while trying to add your entry</h3>'
            +'<pre class="bg-danger">'+JSON.stringify(data_obj, null, 2) +'</pre>'
            +'';


        }
        else if(d1.status == "success")
        {
            ele_this.closest('tr').css('background','red').slideUp('slow');              
        }
    });

    }   

});

});

</script>

ajax.php

//--->Delete row entry  > start
if(isset($_POST['call_type']) && $_POST['call_type'] =="delete_row_entry")

{   

$row_id = app_db()->CleanDBData($_POST['row_id']);   

$q1 = app_db()->select("select * from data where row_id='$row_id'");
if($q1 > 0) 
{
    //found a row to be deleted
    $strTableName = "data";

    $array_where = array('row_id' => $row_id);

    //Call it like this:
    app_db()->Delete($strTableName,$array_where);

    echo json_encode(array(
        'status' => 'success', 
        'msg' => 'deleted entry', 
    ));
    die();
}    
}
//--->Delete row entry  > end

我见过类似this one之类的其他类似问题,但我认为它不适用于我的代码。

我的输出:

enter image description here

1 个答案:

答案 0 :(得分:0)

要实现您想要的目标,您必须以正确的方式选择好的元素。例如,HTML id必须是唯一的,因此给所有元素相同的id="row"是行不通的。使用您的课程就足够了。然后,您必须考虑到each将对所有选择的元素分别执行该函数,因此,如果要对每个元素执行操作,则所有代码都必须在内部。

我通过摆脱allVals变量来优化了一些代码,如果它的唯一目的是测试是否选择了行,则可以直接在选择的内容上测试.length。我重命名了变量,以便更清楚地知道是什么。

这个问题也不是很清楚,是否应该在按钮或每一行中显示“请稍候...删除您的条目”文本,我以为它在按钮中,它将帮助您区分所有元素的选择方式。

//Delete selected rows
$(document).on('click', '.delete_all', function(event) 
{
    event.preventDefault();

    //'click' is called on the button, so 'this' here will be the button
    var button = $(this) ;

    var checked_checkboxes = $(".sub_chk:checked");

    if(checked_checkboxes.length <=0)  
    {  
        alert("Please select row.");  
    }
    else {

        button.html('<p class="bg-warning">Please wait....deleting your entry</p>');

        //next code will be executed for each checkbox selected:
        checked_checkboxes.each(function(){
            var checkbox = $(this);
            var row_id = checkbox.attr('row_id');
            var data_obj=
            {
                call_type: 'delete_row_entry',
                row_id: row_id,
            };

            $.post(ajax_url, data_obj, function(data) 
            { 
                var d1 = JSON.parse(data); 
                if(d1.status == "error")
                {
                    var msg = ''
                    + '<h3>There was an error while trying to add your entry</h3>'
                    +'<pre class="bg-danger">'+JSON.stringify(data_obj, null, 2) +'</pre>'
                    +'';

                    //you still have to do something with your message, keeping in mind that a separate message will be generated for each separate $.post (one is emitted for each checked checkbox)
                }
                else if(d1.status == "success")
                {
                    checkbox.closest('tr').css('background','red').slideUp('slow');              
                }
            });
        });
    }   

});