在Codeigniter中使用AJAX和PHP从MySQL删除记录

时间:2018-11-24 04:08:10

标签: php ajax codeigniter

我想使用AJAX从MySQL数据库表中删除记录。我已经用PHP完成并正常工作。但是我无法通过AJAX来解决这个问题。

AJAX

    $(document).ready(function(){
         $(".confirm").click(function(){
             var bid = $(this).closest("div.box2").find('input[name="dbid"]').val();
             var dataString = 'id='+bid;
             $.ajax({
               type:"POST",
               url:"<?php echo site_url('user/delete_article')?>",
               data:dataString,
               cache:false,
             success: function () {

                 $.alert('Confirmed!');
}
});
 });
 });

PHP

   public function delete_article($id){
        $data['success']='';
        $data['error']='';
        include_once ('query/user_query.php');

        $this->db->where('bid', $id);
        $data['countEarticle'] = $this->db->count_all_results('blog');
        if($data['countEarticle'] >= 1){

            $this->db->where('bid',$id);
            $this->db->delete('blog');

        }
        if($data['countEarticle'] <= 0){

        }          
       }

HTML

   <div class="box-footer box-comments box2" style="display: block;">                       

                <input type="hidden" name="dbid" value="<?php echo $draftfull['bid']?>" >
                <p><btn class="btn btn-azure btn-sm confirm" ><i class="fa fa-trash-o"></i>Delete Article</btn></p>

                  </div>

我需要你的帮助。我究竟做错了什么?

2 个答案:

答案 0 :(得分:2)

尝试此代码:-

ModalUnit

答案 1 :(得分:1)

尝试一下:

<a href="javascript:;" class="btn btn-danger btn-xs mt-sweetalert swtalert" onclick="delete('<?php echo $draftfull["bid"] ?> ')" title="Delete"><span class="fa fa-ban"></span></a>

// ajax

function delete(id) {
   swal({
        title: "Are you sure to delete?",
        text: "Deleting will remove row from listing!",
        type: "error",
        showCancelButton: true,
        confirmButtonClass: "btn-danger",
        confirmButtonText: "Yes!",
        cancelButtonText: "No",
        closeOnConfirm: true,
        closeOnCancel: true
    }, function (isConfirm) {
        if (isConfirm) {
            $.post(
                base_url + "user/delete_article", 
                {bid: id}, 
                function (data) {
                    if (data === "1") {
                        location.reload();
                    } else if (data === "0") {
                        swal("", "Error to deleting data.", "warning");
                    } else {
                        swal("", data[0], "error");
                    }
                });
            }
        });
}

//控制器

function delete_article($id){
    if ( $this->model_name->deleteDataById($this->input->post('bid') ) {
        die('1');
    }
    die('0');
}