单击删除按钮动态删除输入字段的值

用户名

我有一个名为add_field.php和scripts.js的文件。单击添加更多按钮后,我动态添加了输入字段,并将数据保存到数据库中。但是我无法从wordpress数据库中删除输入字段值。所以有人请帮我解决这个问题。我花了很长时间解决此问题,但无法解决。所以请帮帮我。

我的自定义管理菜单页面截图

ajax错误截图

在这里,我附上代码:

add_field.php

add_action('wp_ajax_add_FieldData', 'add_FieldData'); // Logged-in users
add_action('wp_ajax_nopriv_add_FieldData', 'add_FieldData'); // Guest users

add_action('wp_ajax_deleteData', 'deleteData'); // Logged-in users
add_action('wp_ajax_nopriv_deleteData', 'deleteData'); // Guest users

function add_FieldTable() {
    require_once( ABSPATH . '/wp-admin/includes/upgrade.php' );
    global $wpdb;
    $db_table_name = $wpdb->prefix . 'extra_field';
    if ($wpdb->get_var("SHOW TABLES LIKE '$db_table_name'") != $db_table_name) {

        //sql table creation upon activating plugin
        $sql = "CREATE TABLE " . $db_table_name . " ( 
                       `id` int(9) NOT NULL AUTO_INCREMENT,
               `coupon` varchar(50) NOT NULL,
               `discount` int(50) NOT NULL,
            PRIMARY KEY (`id`)
        ) $charset_collate;";
        dbDelta($sql);
    }
}

function ajaxResponse($status, $message) {
    print json_encode(array (
       "status" =>  $status,
       "message" => $message
    ));
    exit;
}

function add_FieldData() {
    global $wpdb;
    $wpdb->show_errors = true;

    //checking whether the coupon and discount has value or not
    $coupon   = isset($_POST['coupon'])   ? $_POST['coupon']   : array();
    $discount = isset($_POST['discount']) ? $_POST['discount'] : array();
    //print_r($coupon); exit;
    # We excepect coupon and doscount to be array.
    # if they are not array then throw exception.
    if (!is_array($coupon) || !is_array($discount)) {
        ajaxResponse('error', 'Invalid data.');
    }

    # Item count can not be empty
    $itemCount = count($coupon);
    if (!$itemCount) {
        ajaxResponse('error', 'Empty data.');
    }
    $dbTableName = $wpdb->prefix . 'extra_field';
    $wpdb->query('START TRANSACTION');

    try {
        # For each item
        for ($i = 0; $i < $itemCount; $i++) {
            $couponName  = isset($coupon[$i])   ? trim($coupon[$i])   : "";
            $discountVal = isset($discount[$i]) ? trim($discount[$i]) : 0;

            # If coupon name is empty then 
            # throw error
            if(!$couponName) {
                $wpdb->query('ROLLBACK');
                ajaxResponse('error', 'Coupon name can not be empty.');
            }

            # Discount value should be numeric (both integer + float)
            # if it violates, throw error
            if (!is_numeric($discountVal)) {
                $wpdb->query('ROLLBACK');
                ajaxResponse('error', 'Discount value should be numeric.');
            }

            //For retreiving one row from the database
            $check = $wpdb->get_row(

                //Preventing from sql injection attacks
                $wpdb->prepare(
                    "SELECT coupon 
                       FROM $dbTableName 
                      WHERE coupon = %s", array($couponName)
                )
            );

            if (!$check) {
                $a = $wpdb->insert($dbTableName, array(
                    'coupon' => $couponName,
                    'discount' => $discountVal
                ));

            } else { 
                $a = $wpdb->update($dbTableName, 
                    array('discount' => $discountVal), 
                    array('coupon' => $couponName)
                );
            } 
        }
        $wpdb->query('COMMIT');
        ajaxResponse('success', 'Coupon name and their respective discounts saved successfully..'); 
    } catch (Exception $ex) {
        $wpdb->query('ROLLBACK');
        if (WP_DEBUG) {
            ajaxResponse('error', $ex->getMessage());
        }
        ajaxResponse('error', 'Something went wrong.');
    }
}

function deleteData() {
     global $wpdb;
    $a = $wpdb->delete($dbTableName, array(
                    'coupon' => id
                ));
}
function custom_inputForm() {

    echo '
          <br>
          <strong>Welcome. Please Enter Coupon Name  & Discount[in %]</strong>
           <form action ="' . $_SERVER['REQUEST_URI'] . '" method = "post">
          <div class="input_fields_wrap">
          <button class="add_field_button">Add More</button><br>
          <label for="coupon">Coupon Name:</label>
          <input id ="coupon" type="text" name="coupon[]" value = "">

          <label for="discount">Discount in %:</label>
          <input id ="discount" type="text" name="discount[]" value = "">
          </div>
          <br>
          <input id="submit" type= "submit" name="submit" value="Submit"/>
          </form>';
}
?>

scripts.js

/**
 * Javascript for collecting Admin Input Data
 * Created On: Aug 17, 2016
 * Author : BDT
 */

(jQuery)(document).ready(function () {

    //Admin clicks on submit button
    jQuery("#submit").click(function (e) {
        e.preventDefault();

        var couponNumber = new Array();
        jQuery("input[name='coupon[]']").each(function() {
            couponNumber.push(jQuery(this).val());
        });

        var discountItem = new Array();
        jQuery("input[name='discount[]']").each(function(){
            discountItem.push(jQuery(this).val());
        });

        //Passing the values to the corresponding function for fetching 
        jQuery.ajax({
            type: 'POST',
            url: ajaxurl,
            data: {
                action: "add_FieldData",
                coupon: couponNumber,
                discount: discountItem
            },            
            success: function (data) {
                data = JSON.parse(data);
                alert(data.message);
            }
        });
    });
    var max_fields = 15; //maximum input boxes allowed
    var wrapper = (jQuery)(".input_fields_wrap"); //Fields wrapper
    var add_button = (jQuery)(".add_field_button"); //Add button ID
    var fieldHTML = '<div><label for="coupon">Coupon Name:</label><input type= "text" name = "coupon[]" value=""/><label for="discount">Discount in %:</label><input type="text" name="discount[]" value =""/><button class="remove_field">Remove</button></div>';

    var x = 1; //initial text box count
    (jQuery)(add_button).click(function (e) {
        e.preventDefault();
        if (x < max_fields) { //Check maximum number of input fields
            x++; //Increment field counter
            (jQuery)(wrapper).append(fieldHTML); // Add field html
        }
    });

    (jQuery)(wrapper).on("click", ".remove_field", function (e) { //user click on remove link
        e.preventDefault();
        var id = document.getElementById('coupon').value;
        alert(id);
        jQuery.ajax({
            type: 'POST',
            url: ajaxurl,
            data: {
              action: 'deleteData',
              coupon: id
            },success: function (data) {
                data = JSON.parse(data);
                alert(data.message);
            }
        });
        (jQuery)(this).parent('div').remove();
        x--;
    })
});
Ben Bodan

我认为您忘记了在delete函数中声明数据库表名称,并且还需要从ajax帖子中获取ID。

function deleteData() {
        global $wpdb;
        //declare db table 
        $dbTableName = $wpdb->prefix . 'extra_field';
        //Get coupon id  from ajax post 
        if (isset($_POST['coupon'])){
            $id = $_POST['coupon'];
        }else{
            $id = "";
         }

        $a = $wpdb->delete($dbTableName, array(
                        'coupon' => $id //use the coupon id you get from ajax post 
                    ));
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章