【问题标题】:AJAX for successful php :: delete checked table list :: using hyperlink NOT inputAJAX 成功的 php :: 删除检查表列表 :: 使用超链接不输入
【发布时间】:2014-11-05 07:30:21
【问题描述】:

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

我试图让它工作,但没有运气。有人可以看一下编码和脚本,看看您是否能发现任何错误?

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

表格

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

【问题讨论】:

  • 您收到的错误是什么?
  • 第一个错误告诉我 var count 在 ajax 中写错了
  • $count 是您在 php 脚本中声明的变量吗?
  • @Ohgodwhy yes $count = mysqli_num_rows($result); 成功生成准确计数。
  • 你将在 3 分钟内被 hack,永远不要在你的代码中使用这种逻辑$chkbx = $_POST['chkbx']; $del_id = $chkbx[$i]; WHERE unit_id='".$del_id."'";search sql injection

标签: php mysql ajax delete-row sql-delete


【解决方案1】:

通过挖掘大量书签,我找到了一个我希望实现的示例。在摆弄了 sn-ps 的代码之后,我终于让 ajax 像我希望在项目的这一步中实现的那样工作。

为了希望帮助其他人搜索此内容,我在下面提供了在我的测试中完美运行的 ajax/jq/js 和 php 的所有编码。

这段代码的工作原理

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

希望这可以帮助那里的人。如果有人看到我可能遗漏的任何其他错误,请随时分享,以取得更大的利益。干杯。

ajaxDelete.js

注意事项:
1.) 将图片(按钮)href 更新为href="deleteRecord.php"
2.) 研究并发现了一个更好的approach,它将计数减少到仅检查(我认为如果表增长到大量行,这会更有效(更快)。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 2020-12-19
    • 2020-09-09
    相关资源
    最近更新 更多