jQuery添加的表单行未提交

jQuery added form row not submited

提问人:Eduard 提问时间:7/28/2023 最后编辑:Eduard 更新时间:7/28/2023 访问量:41

问:

我正在创建自定义 Worpdress 插件。我有表格。我有按钮,可以将新行添加到表单中,并调用ajax将行添加到数据库中。问题是,如果我添加新行,更改一些输入然后保存它,更改不会传播到数据库。

如果我添加新行,刷新页面,然后进行一些更改并提交表单,它就可以正常工作。

Ajax 调用:

    jQuery(document).ready(function ($) {
        jQuery("#eda-add-new-row").click(function (e) {
            e.preventDefault();
            nonce = jQuery(this).attr("data-nonce");
            jQuery.ajax({
                type: "post",
                dataType: "json",
                context: this,
                url: myAjax.ajaxurl,
                data: {action: "eda_add_row", nonce: nonce},
                success: function (response) {
                    if (response.type == "success") {
                        jQuery("#eda-form-table-body").append(response.like_count);
                        $('#eda-add-new-row .spinner').css('visibility', 'hidden');
                        $('#eda-add-new-row .spinner').css('display', 'none');
                    } else {
                        alert("Někde se stala chyba. Volejte Edu.)");
                    }
                }
            });
        });
});

处理 AJAX 请求的函数:

function eda_add_row() {
    if (!wp_verify_nonce($_REQUEST['nonce'], "my_user_like_nonce")) {
        exit("Woof Woof Woof");
    }

    $result['type'] = "success";
    $result['like_count'] = eda_add_new_row(0,0,0,0,0,0,0,true);

    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        echo json_encode($result, JSON_HEX_QUOT | JSON_HEX_TAG);
    } else {
        header("Location: " . $_SERVER["HTTP_REFERER"]);
    }
    die();
}

返回新行的 HTML 的函数:

<?php
function eda_add_new_row($row_id=0,$customer_id=0,$brand_id=0,$category_id=0,$product_id=0,$discount=0,$table_order=0,$add_to_db=false,$color='#fff'){

    global $wpdb;

if ($add_to_db){
    $row = $wpdb->prefix . 'eda_custom_pricing_users';
$data = array(
    'customer_id'   => $customer_id,
    'brand_id' => $brand_id,
    'category_id'  => $category_id,
    'product_id'  => $product_id,
    'discount'  => $discount,
    'table_order'  => $table_order,
);
$format = array( '%d', '%d', '%d', '%d', '%d', '%d' );
$wpdb->insert( $row, $data, $format );

}
        ob_start();
        $selected = ' selected';
    ?>

    <tr style="background-color: <?php echo $color;?>;">
        <td>
        <input name="row_id[]" type="hidden" value="<?php echo $row_id;?>">
            <select name="customers[]" id="customers-select">
                <option value="0">Vyberte zákazníka</option>
                <?php
                $customers = get_all_wholesale_customers();
                foreach ($customers as $customer) {
                    echo '<option'.(($customer->get_id()==$customer_id) ? $selected : ''). ' value="' . $customer->get_id() . '">' . $customer->get_billing_first_name() . ' ' . $customer->get_billing_last_name() . ' (' .
                        $customer->get_billing_company() . ')' . '
                </option>';
                } ?>
            </select>
        </td>
        <td>
            <select name="brands[]" id="brands-select">
                <option value="0">Všechny značky</option>
                <?php
                $brands = eda_get_all_brands();
                foreach ($brands as $brand) {
                    echo '<option'.(($brand->term_id==$brand_id) ? $selected : ''). ' value="' . $brand->term_id . '">' . $brand->name . '</option>';
                }
                ?>
            </select>
        </td>
        <td>
            <select name="categories[]" id="categories-select">
                <option value="0">Všechny kategorie</option>
                <?php
                $categories = eda_get_top_level_categories();
                foreach ($categories as $category) {

                    echo '<option'.(($category->term_id==$category_id) ? $selected : ''). ' value="' . $category->term_id . '">' . $category->name . '</option>';

                }
                ?> </select>
        </td>
        <td>
            <select name="products[]" id="products-select">
                <option value="0">Všechny produkty</option>
                <?php

                $products = eda_make_ordered_products_list(eda_get_all_b2b_products(0));

                usort($products, function ($a, $b) {
                    return [$a['BRAND'], $a['NAME']] <=> [$b['BRAND'], $b['NAME']];
                });

                foreach ($products as $product) {
                    echo '<option'.(($product['ID']==$product_id) ? $selected : ''). ' value="' . $product['ID'] . '">' . $product['BRAND'] . ' - ' . $product['NAME'] . ' (' . $product['SKU'] . ')</option>';
                }


                ?></select>
        </td>
        <td><input type="number" id="discount" name="discount[]"
                   min="0" max="100" value="<?php echo $discount;?>"></td>
        <td>
        <?php $nonce = wp_create_nonce("delete_row_nonce");?>
            <button type="button" class="button action eda-remove-row" value="<?php echo $row_id;?>"  data-nonce="<?php echo $nonce; ?>">Odstranit pravidlo</button>
        </td>
        <td>
            <img class="eda-drag-row" src="<?php echo plugin_dir_url(__FILE__); ?>/img/drag.png" alt="">
        </td>

    </tr>
    <?php

       $html =ob_get_contents();
    ob_end_clean();
        return $html;
   }

函数,用于初始化插件页面并呈现表格:

<?php
function eda_init_user_discounts_page() {


if ($_GET["eda_admin_add_notice_user_discounts"]) {
    ?>
    <div class="notice notice-success is-dismissible">
        <p><?php echo $_GET["eda_admin_add_notice_user_discounts"]; ?></p>
    </div>
    <?php
}

if ($_GET["eda_admin_add_notice_user_discounts_error"]) {
    ?>
    <div class="notice notice-error is-dismissible">
        <p><?php echo $_GET["eda_admin_add_notice_user_discounts_error"]; ?></p>
    </div>
    <?php
}

?>
<div class="eda-custom-pricing">
    <h1>Eda Custom Pricing</h1>
    <h2>Zákaznické slevy</h2>
    <div class="wrap">
        <ul>
            <li>
                Priorita slev má sestupnou tendenci, tedy pokud např. jeden zákazník má slevu na celou značku a pak slevu na konkrétní produkt, sleva na produkt
                musí být první, sleva na značku jako druhá. Jinak řečeno specifičtější slevy musí být nahoře, všeobecnější níže.
            </li>
            <li>
                Pořadí slev lze určovat přetažením řádku tabulky na požadované místo (ikona 6 teček v posledním sloupci).
            </li>

            <li>
                <strong>Po každé úpravě v tabulce je nutné uložit změny. </strong>

            </li>
        </ul>

        <form method="post" action="<?php echo admin_url() . "admin-post.php"; ?>" id="user_discounts_form">
<?php $sort_rows_nonce = wp_create_nonce("sort_rows_nonce");?>
            <input id="hidden-input-nonce" type="hidden" name="action" value="eda_submit_form_user_discounts" data-nonce="<?php echo $sort_rows_nonce;?>">
            <table id="GFG" class="eda-form-table wp-list-table widefat auto striped table-view-list">
                <thead>
                <tr>
                    <th scope="col" class="manage-column column-title column-primary">Zákazník</th>
                    <th scope="col" class="manage-column column-title column-primary">Značka</th>
                    <th scope="col" class="manage-column column-title column-primary">Kategorie</th>
                    <th scope="col" class="manage-column column-title column-primary">Produkt</th>
                    <th scope="col" class="manage-column column-title column-primary">Sleva (%)</th>
                    <th scope="col" class="manage-column column-title column-primary">Odstranit</th>
                    <th scope="col" class="manage-column column-title column-primary">Přesunout</th>
                </tr>
                </thead>


                <tbody id="eda-form-table-body">
                <?php
                //echo eda_add_new_row();
                echo eda_retrieve_discount_rules();
                ?>
                </tbody>
            </table>
            <button class="button action" id="eda-submit" type="submit" name="user_discounts_submit">
                <span class="spinner"></span>
                Uložit změny
            </button>

            <?php
            $nonce = wp_create_nonce("my_user_like_nonce");
            ?>
            <button class="button action" id="eda-add-new-row" type="button" name="eda_add_new_row" data-nonce="<?php echo $nonce; ?>">
                <span class="spinner"></span>
                Přidat nové pravidlo
            </button>
            <div id="divMsg">
                Probíhá ukládání. Nezavírejte toto okno, dokud se operace nedokončí.

            </div>
        </form>

        <?php //eda_vytvor_var_dump( eda_get_top_level_categories() ); ?>
        <?php //eda_vytvor_var_dump( get_all_wholesale_customers() ); ?>
        <?php //eda_retrieve_discount_rules(); ?>
        <?php //eda_vytvor_var_dump( eda_make_ordered_products_list( eda_get_all_b2b_products( 0 ) ) ); ?>


    </div>

    <?php
    }

我搜索了许多不同的主题,但都没有找到任何解决方案。所有主题都只处理基本错误,如无效的html标记等......

php jquery ajax wordpress 表单

评论

1赞 Travis Heeter 7/28/2023
欢迎来到 SO!一般来说,将所有代码都发布到一个问题中绝不是一个好主意。理想情况下,你想要一个陌生人可以看不到 5 分钟的东西,弄清楚你想做什么以及你的问题是什么——这是获得帮助的最佳方式。99%的情况下,在这样做的过程中,你会找到自己的答案。
0赞 ADyson 7/28/2023
你真的做过调试吗?尝试将问题范围缩小到代码的更具体区域。另请参阅如何提问以及如何制作问题的最小可重现示例
0赞 Eduard 7/28/2023
对不起,下次我会做得更好。几个小时后,我已经解决了问题。我没有将新创建的表条目的row_id传递回html,所以它是0。显然,如果我更改了数据并提交了表单,则不会更新row_id为 0 的行。

答: 暂无答案