AJAX成功的php::删除选中的表列表::使用超链接NOT输入


AJAX for successful php :: delete checked table list :: using hyperlink NOT input

项目焦点:从表单中删除多个已检查的表列表。
规格:
1.)使用<a href>超链接删除操作(非<input type="submit"
2.)我想用AJAX来实现这一点,包括confirm&错误/成功响应
删除操作的状态:我终于可以用我的代码删除多个复选框了请参阅下面成功的PHP代码段
注意:当前正在使用<input type="submit" name="delete>"在同一页面中处理成功的$_POST编码

我试着让它发挥作用,但没有成功。有人能看一下编码吗;脚本,看看你是否能发现任何错误

我的想法(但不确定):
1) ajax var formData写错了,实现了同时获取$delete = $_POST['delete'];$chkbx = $_POST['chkbx'];
2) <a href"#" id="#btn_del"可能应该尝试使用.post 而不是.click

表单

<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" name="recordsForm" id="recordsForm">

按钮

更新(针对规范#1)href更新为href="deleteRecord.php"

<li class="button" id="toolbar-del">
    <a href="#" title="Delete" id="btn_del">
        <span class="icon-16-delete dead"></span>
        Delete
    </a>
</li>

PHP代码段:

这段代码目前包含在表单的底部。稍后,我想将其作为一个函数移动到一个单独的actions.php页面,该页面将包括其他按钮操作(编辑、复制、存档等)。现在,我很乐意将它移到deleteRecord.php页面&用这个AJAX调用它。

<?
                                // Check if DELETE button active, start this
$delete         = $_POST['delete'];
$chkbx          = $_POST['chkbx'];
if($delete){
 for($i=0;$i<$count;$i++){
   $del_id  = $chkbx[$i];
   $sql     = "DELETE FROM ".ID_TABLE." WHERE unit_id='".$del_id."'";
   $result  = mysqli_query($dbc,$sql);
 }
                                // if successful redirect to delete_multiple.php
 if($result){
    echo "<meta http-equiv='"refresh'" content='"0;URL=records_manager.php'">";
    }else{
        echo "Error: No luck";
    }
  }
mysqli_close($dbc);
?>

ajaxDELETE

// ajaxDelete.js
$(document).ready(function() {
                                                    // When TRASH button is clicked...
$('#btn_del').click(function(event) {
    e.preventDefault();                             // stop the form submitting the normal way
                                                    // and refreshing the page  
    // Get the form data                            // there are many ways to get this data using jQuery
    // ----------------------------------           // (you can use the class or id also)
    var formData = {
              'chkbx'   : $('input[name=chkbx]').val(),
              'count'   : $count[0]
    // Process the form
    // ================
    $.ajax({
              type      : 'POST',                   // define the type of HTTP verb we want to use
              url       : 'deleteRecord.php',       // the url where we want to POST
              data      : formData,                 // our data object
              dataType  : 'json',                   // what type of data do we expect back from the server
              encode    : true
          })
                                                    // using the .done(), 
                                                    // promise callback
    .done(function(data) {                      
        window.console.log(data);                   // log data to the console so we can see
        // Handle ERRORS
        if ( ! data.success) {                                      
            if (data.errors.chkbx) {                
                $('.Records_Found').addClass('has-error');
                $('.Records_Found').append('<div class="help-block">'+ data.errors.chkbx + '</div>');   
            }
        }                                           // end if ERRORS
        else {
            $('.Records_Found').append('<div class="alert alert-success" id="valid_success">'+ data.message + '</div>');
    // After form submission,
                                                    // redirect a user to another page
        window.location = 'records_manager.php'; 
              }
          })
          .fail(function(data) {                    // promise callback
          window.console.log(data);  });            // show any errors in console
                                                    // NOTE: it's best to remove for production
          event.preventDefault();                   // stop the form from submitting the normal way
                                                    // and refreshing the page  
      });                                           // end submit button
    });                                             // end document ready

删除记录.php

<?php
// FUNCTION to DELETE
// ===========================
// :checked existing unit data
$errors = array();                      // array to hold validation errors
$data   = array();                      // array to pass back data
if ( empty($_POST['chkbx']))                // if empty, populate error
    $errors['chkbx'] = 'No items have been checked yet.';
// ERROR! Return a response
if ( ! empty($errors)) {        
    $data['success'] = false;           // any errors = return a success boolean of FALSE
    $data['errors']  = $errors;         // return those errors
} else {                            
// NO ERROR... Carry on                     // Process the form data  
    require_once('config.php');             // Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
        or die ('Error connecting to MySQL server.'.$dbc);
                                            // Check if DELETE 
$delete         = $_POST['delete'];
$chkbx          = $_POST['chkbx'];
$count          = $_POST['count'];
if($delete){
    for($i=0;$i<$count;$i++){
        $del_id     = $chkbx[$i];
        $sql        = "DELETE FROM ".ID_TABLE." WHERE unit_id='".$del_id."'";
        $result     = mysqli_query($dbc,$sql);
    }
                                            // if successful redirect
    if($result){
            echo "<meta http-equiv='"refresh'" content='"0;URL=records_manager.php'">";
    }else{
            echo "Error: No luck";
    }
}
mysqli_close($dbc);                             // close DB connection
}
$data['success'] = true;                        // show a message of success 
$data['message'] = 'Success!';                  // and provide a true success variable
}
echo json_encode($data);                        // return all our data to an AJAX call  
}                                               // end else NO ERRORS, process form 
?>

在大量书签中,我找到了一个我希望实现的目标的例子。在处理了一些代码片段之后,我终于让ajax发挥了我希望在项目的这一步中实现的作用

为了帮助其他人搜索这一点,下面,我提供了ajax/jq/js&php在我的测试中完美地工作

此代码的工作方式

  • 按钮(超链接outside of the formNOT an input button)链接到deletedRecord.php,但脚本使用e.preventDefault()覆盖链接
  • JQ用于构建检查的行ID&通过AJAX将它们发送到deletedRecord.php
  • deleteRecord.php分解数组,计数检查的ID总数,最后循环查询以删除每个ID
  • 成功完成后,回显1的响应以触发成功操作

希望这能帮助到其他人。如果有人看到我可能错过的任何其他错误,请随时分享,以获得更大的好处。干杯

ajaxDelete.js

备注:
1.)将图像(按钮)href更新为href="deleteRecord.php"
2.)研究;找到了一种更好的方法,将计数减少到只检查(我认为这在表增长到大量行的情况下会更有效(更快)。

$(document).ready(function() {
$('#btn_del').click(function(e) {
e.preventDefault(); 
    page    = $(this).attr("href");
    ids     = new Array()
    a       = 0;
    $(".chk:checked").each(function(){
       ids[a] = $(this).val();
       a++;
})   
      // alert(ids);
if (confirm("Are you sure you want to delete these courses?")) {
     $.ajax({
            url         :   page,
            type        :   "POST",
            data        :   "id="+ids,
            dataType    :   'json',
            success     :   function(res) {
                             if ( res == 1 ) {
                                 $(".chk:checked").each(function() {
                                     $(this).parent().parent().remove();
                                  })        // end if then remove table row
                                }           // end if res ==1
                             }              // end success response function
            })                              // end ajax
     }                                      // end confirmed
return false;
});                                         // end button click function
});                                         // end doc ready

删除记录.php

<?php
require_once('config.php');                 // Connect to the database
    $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
        or die ('Error connecting to MySQL server.'.$dbc);
    $del_id = explode(",",$_POST['id']);
    $count = count($del_id);
        if (count($count) > 0) {
            foreach ($del_id as $id) {
                      $sql = "DELETE FROM ".ID_TABLE."
                              WHERE unit_id='" . $id . "'";
                      $result = mysqli_query($dbc,$sql) 
                              or die(mysqli_error($dbc)); 
            }                                   // end for each as
        mysqli_close($dbc);                     // close MySQL
        echo json_encode(1);                    // Return json res == 1
                                                // this is used for the SUCCESS action
        }                                       // end if count > 0
?>