jQuery生成的在$ _POST上无法识别的元素

我正在使用PHP和jQuery开发Wordpress插件,当<select>输入更改时,下面的函数会被调用,到目前为止,它可以按预期工作并且可以正确生成输入,但是当我提交表单时,在$_POST中调用时,生成的元素是不确定的。

<?php

function random_event() {
    global $wpdb;

    //Table for all the event details
    $tablename = $wpdb->prefix."random_event";

    // Table to store all banner stores
    $tablename2 = $wpdb->prefix."random_event_banner_stores";

    //Table for store all poster
    $tablename4 = $wpdb->prefix."random_event_poster";

    // Table storing all user registrations
    $tablename3 = $wpdb->prefix."random_event_winners";

    //Junction table to map the poster to banner store
    $tablename5 = $wpdb->prefix."random_event_poster_banner";

    //Junction table to map the poster to event
    $tablename6 = $wpdb->prefix."random_event_poster_event";


    $tablename5 = $wpdb->prefix."random_event_poster_banner";

    $sql = "select event.*,banner.name as banner_name,banner.id as banner_id from $tablename as event left join $tablename2 as banner on banner.id = event.store_id";
    $results = $wpdb->get_results($sql);

    $update_this_event = -1;
    $banner_stores = [];
    //Deletion
    if(isset($_POST['delete_event'])) {


        $event_id = esc_sql($_POST['event_id']);

        $sql = "DELETE from $tablename WHERE id= '" . $event_id . "'";

        try{
            $event = $wpdb->query($sql);
        }
        catch (Exception $e) {
            echo "<script>console.log($e);</script>";
        }

    } else if(isset($_POST['update_event'])){

        $update_this_event = intval(esc_sql($_POST['event_id']));
        $banner_store_id = esc_sql($_POST['banner_id']);
        $name = esc_sql($_POST['banner_store_name']);
        $description = esc_sql($_POST['banner_store_description']);
        $location_note = esc_sql($_POST['banner_store_location_note']);
        $address = esc_sql($_POST['banner_store_address']);
        $status = esc_sql($_POST['banner_store_status']);

        $sql = "UPDATE $tablename SET name = '" . $name . "',description = '" . $description . "',location_note = '" . $location_note . "',address = '" . $address . "',status =  '" . $status . "' WHERE id = '" . $banner_store_id . "'";

        try{
            $participants = $wpdb->query($sql);
        }
        catch (Exception $e) {
            echo "<script>console.log($e);</script>";
        }
    } else if(isset($_POST['select_update_event'])){

        $update_this_event = intval(esc_sql($_POST['event_id']));

        // $pssql = "select * from $tablename2";
        // $banner_stores = $wpdb->get_results($pssql);

        $pssql = "select $tablename2.* from $tablename2 left join $tablename on $tablename2.id = $tablename.store_id where $tablename.store_id is null";
        // $pssql = "select * from $tablename2";
        $banner_stores = $wpdb->get_results($pssql);

        $pssql2 = "select $tablename2.* from $tablename2 left join $tablename on $tablename2.id = $tablename.store_id where $tablename.id = '".$update_this_event."'";
        $current_banner_store = $wpdb->get_results($pssql2);

        if(count($current_banner_store) != 0) {
            array_push($banner_stores,$current_banner_store[0]);
        }

        $poster_sql = "select ap.*,a.name as poster_name,ap.qty as qty from $tablename6 as ap inner join  $tablename4 as a on a.id = ap.poster_id where ap.event_id = $update_this_event";

        $poster_event = $wpdb->get_results($poster_sql);

        $poster_petone = [];
        foreach($results as $result) {
            if($result->id == $update_this_event) {
                $poster_sql = "select a.* from $tablename5 as ap inner join $tablename4 as a on a.id = ap.poster_id where banner_store_id = ".$result->store_id;

                $poster_petone = $wpdb->get_results($poster_sql);
            }
        }


    }else if(isset($_POST['cancel_update_event'])){

        $update_this_event = -1;

    }else if (isset($_POST['save_update_event'])) {

        $update_this_event = intval(esc_sql($_POST['event_id']));
        $title = esc_sql($_POST['title']);
        $qty = 0;
        $description = esc_sql($_POST['description']);
        $prize = esc_sql($_POST['prize']);
        $event_code = esc_sql($_POST['event_code']);
        $event_from = esc_sql($_POST['event_from']);
        $event_to = esc_sql($_POST['event_to']);
        $banner_store_id = esc_sql($_POST['banner_store_id']);

        if(isset($_POST['poster_ids'])){
            $poster_ids = $_POST['poster_ids'];
            $poster_qtys = $_POST['poster_qty'];
        }

        $query = "UPDATE $tablename set title='$title',description='$description',event_code='$event_code',valid_from='$event_from',valid_to='$event_to',store_id='$banner_store_id',prize = '$prize' ";
        $query .= "where id = $update_this_event";

        $result_insert = $wpdb->query($query);

        $delete_query = "delete from $tablename6 where event_id =  $update_this_event";
        $wpdb->query($delete_query);

        for($i = 0; $i < count($poster_ids); $i++) {
            $poster_id = esc_sql($poster_ids[$i]);
            $poster_qty = esc_sql($poster_qtys[$i]);

            $poster_query = "INSERT INTO $tablename6 (event_id,poster_id,qty) values ";
            $poster_query .= "('$update_this_event','$poster_id','$poster_qty');";

            $poster_insert = $wpdb->get_results($poster_query);
            $poster_result = $wpdb->insert_id;
        }

        $update_this_event = -1;

        $sql = "select event.*,banner.id as banner_id from $tablename as event left join $tablename2 as banner on banner.id = event.store_id";
        $results = $wpdb->get_results($sql);
    }

    ?>

    <style type="text/css" emb-not-inline="">

    .table-container {
        width: 100%;
        max-width: 100%;
        overflow-x: auto;
    }

    .hidden {
        display: none;
    }

    .banner-button {
        background-color: #ffffff;
        border-radius: 5px;
        padding: 5px;
        font-size: 13px;
        min-width: 75px;
    }

    table {
        border: none;
        text-align: center;
    }

    table tr:nth-child(even) {
        background-color: #dddddd;
    }

    table tr:nth-child(odd) {
        background-color: #ffffff;
    }

    table th {
        background-color: #23282d;
        color: #ffffff;
    }

    table th:first-child{
        border-radius: 20px 0px 0px 0px;
    }

    table th:last-child{
        border-radius: 0px 20px 0px 0px;
    }

    table {
        border-radius: 20px 20px 0px 0px;
    }

    </style>

    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <link rel="stylesheet" href="/resources/demos/style.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

    <h1>View All events</h1>

    <br/>

    <div class="table-container" style="
    width: 100%;
    max-width: 100%;
    overflow-x: auto;
    ">

    <table cellpadding="10" border=1 style="border-style: solid #AAA">
        <tr>

            <th>Title</th>
            <th>Description</th>
            <th>Prize</th>
            <th>event Code</th>
            <th>banner Store</th>
            <th>poster Qty</th>
            <th>Validity</th>
            <th>QR code</th>
            <th>action</th>

        </tr>

        <?php
        foreach($results as $result) {

            if($update_this_event == $result->id) { ?>
                    <tr>
                        <form method="post" name="formtest1" id="formtest1">

                        <td valign="top"><input type="text" name="title" value="<?php echo $result->title ?>"/> </td>
                        <td valign="top"><input type="text" name="description" value="<?php echo $result->description ?>"/> </td>
                        <td valign="top"><input type="text" name="prize" value="<?php echo $result->prize ?>"/> </td>

                        <td valign="top"><input type="text" name="event_code" value="<?php echo $result->event_code ?>"/> </td>
                        <td valign="top">

                            <!-- <select onChange="changebanner(this)" id="banner_store_id" name="banner_store_id"> -->
                            <select id="banner_store_id" name="banner_store_id">
                                <?php
                                foreach($banner_stores as $pstore) {

                                    if($result->banner_id == $pstore->id) {
                                        ?>
                                        <option SELECTED value="<?php echo $pstore->id?>"> <?php echo $pstore->name ?></option>
                                        <?php
                                    }else {
                                        ?>
                                        <option value="<?php echo $pstore->id?>"> <?php echo $pstore->name ?></option>
                                        <?php
                                    }
                                }
                                ?>
                            </select>
                        </td>
                        <td valign="top">
                            <div id="poster_div">

                                <table border="0" cellpadding=5>
                                    <?php
                                    if(count($poster_event) == 0) {

                                        for($i = 0; $i < count($poster_petone); $i++)
                                        {
                                            ?>
                                            <tr>
                                                <td>
                                                    <input type="hidden" name="poster_ids[]" value="<?php echo $poster_petone[$i]->id?>"><?php echo $poster_petone[$i]->name?>
                                                </td>
                                                <td>
                                                    <input type="text" name="poster_qty[]" placeholder= "Qty Allocation" value="<?php echo $poster_petone[$i]->qty ?>">
                                                </td>

                                            </tr>
                                            <?php
                                        }
                                    }else {
                                        for($i = 0; $i < count($poster_event); $i++)
                                        {
                                            ?>
                                            <tr>
                                                <td><input type="hidden" name="poster_ids[]" value="<?php echo $poster_event[$i]->poster_id?>"><?php echo $poster_event[$i]->poster_name?></td>
                                                <td><input type="text" name="poster_qty[]" placeholder= "Qty Allocation" value="<?php echo $poster_event[$i]->qty?>"></td>
                                            </tr>
                                            <?php
                                        }
                                    }?>
                                </table>
                            </div>
                        </td>
                        <td valign="top"><input id="event_from" name="event_from" type="text" value="<?php echo $result->valid_from ?>"/> - <input name="event_to" id="event_to" type="text" value="<?php echo $result->valid_to ?>"/> </td>
                        <td valign="top"></td>
                        <td valign="top">
                            <input type="hidden" name="event_id" value="<?php echo $result->id ?> ">
                            <input type="submit" name="save_update_event" value="save" class="banner-button">
                            <input type="submit" name="cancel_update_event" value="cancel" class="banner-button">
                        </td>

                        </form>
                    </tr>
                <?php
            } else {
                ?>
                <tr>
                    <td valign="top"><?php echo $result->title ?> </td>
                    <td valign="top"><?php echo $result->description ?> </td>
                    <td valign="top"><?php echo $result->prize ?> </td>
                    <td valign="top"><?php echo $result->event_code ?> </td>
                    <td valign="top"><?php echo $result->banner_name ?> </td>
                    <td valign="top"><?php get_poster_of_event($result->id ) ?> </td>
                    <td valign="top"><?php echo $result->valid_from ?> - <?php echo $result->valid_to ?></td>
                    <td valign="top"><?php generate_random("https://generic.com/event/?random=".$result->event_code,$result->title) ?> </td>
                    <td valign="top">
                        <form method="post" name="formtest" id="formtest">
                            <input type="hidden" name="event_id" value="<?php echo $result->id ?> "/>
                            <input type="submit" name="delete_event" value="delete" class="banner-button"/>
                        </form>
                        <form method="post" name="formtest" id="formtest">
                            <input type="hidden" name="event_id" value="<?php echo $result->id ?> "/>
                            <input type="submit" name="select_update_event" value="update" class="banner-button"/>
                        </form>
                    </td>

                </tr>
                <?php
            }
        }
        ?>
    </table>
</div>

<script>

let jQueryNC = jQuery.noConflict();

jQueryNC( function() {
    jQueryNC( "#event_to" ).datepicker({ dateFormat: 'yy-mm-dd' });
    jQueryNC( "#event_from" ).datepicker({ dateFormat: 'yy-mm-dd' });

} );

jQueryNC("body").on("change","#banner_store_id",function() {
  changebanner(jQueryNC(this));
});

function changebanner(e){
    let jQueryNC = jQuery.noConflict();
            jQueryNC( "#poster_div" ).html("Loading...");
            let formData = new FormData(); // creates an object,optionally fill from <form>
            let value = jQueryNC("#banner_store_id").val();
            console.log(e.value);

            formData.append('poster_id',value);
                formData.append('action','get_poster');

                let xhr = new XMLHttpRequest();
                xhr.open("POST","/admin/admin-post.php");
                xhr.send(formData);

                xhr.onload = () => {
                    let posters = JSON.parse(xhr.response);
                    let htmldiv = '<table border=0 cellpadding=5>';

                    for(let i = 0; i < posters.length; i++)
                    {
                        htmldiv += '<tr>';
                        htmldiv += '<td><input type="hidden" name="poster_ids[]" value="'+posters[i].id+'">'+posters[i].name+'</td>';
                        htmldiv += '<td><input type="text" name="poster_qty[]" placeholder= "Qty Allocation" value="'+posters[i].qty+'"></td>';
                        htmldiv += '</tr>';

                    }
                    htmldiv += '</table>';

                    jQueryNC("#poster_div").html(htmldiv);
                }

        }
</script>

<?php
} ?>

说明:在不更改选择输入的情况下,提交时可以识别容器div中的输入而没有任何错误,但是通过changebanner更改了容器div的内容时;创建了新的输入和表,但是如果提交了新输入和表,则$ _POST ['poster_ids']

不能识别出poster_ids []之类的输入。

EDIT (添加了完整的代码),希望可以澄清问题

tooy12345 回答:jQuery生成的在$ _POST上无法识别的元素

尝试在选择中取出onchange(this),而使用jQuery on。(“ change”)。

没有看到确切的错误或您尝试执行的操作,很难准确地说出,但是尝试访问尚未创建的变量通常会给出未定义的信息,因为您试图在它尚未存在之前对其进行访问。通过使用jQuery on函数,您可以找到DOM加载后添加的内容。

祝你好运。

$("body").on("change","#data_store_id",function() {
  changeSELECTED($(this));
});

function changeSELECTED(e) {

  let jQueryNC = jQuery.noConflict();
  jQueryNC("#container_div").html("Loading...");
  let formData = new FormData(); // creates an object,optionally fill from <form>

  formData.append('data_id',e.value);
  formData.append('action','get_data');

  let xhr = new XMLHttpRequest();
  xhr.open("POST","/adminfolder/admin-post.php");
  xhr.send(formData);

  xhr.onload = () => {

    let datas = JSON.parse(xhr.response);
    let htmldiv = '<table border=0 cellpadding=5>';
    for (let i = 0; i < datas.length; i++) {
      htmldiv += '<tr>';
      htmldiv += '<td><input type="hidden" name="data_ids[]" value="' + datas[i].id + '">' + datas[i].name + '</td>';
      htmldiv += '<td><input type="text" name="data_qty[]" placeholder= "Qty Allocation" value="' + datas[i].qty + '"></td>';
      htmldiv += '</tr>';

    }
    htmldiv += '</table>';

    jQueryNC("#container_div").html(htmldiv);
  }

}
<select id="data_store_id" name="data_store_id">
  <?php
        foreach($data_stores as $dstore) {
        if($result->data_id == $dstore->id) {
            ?>
    <option SELECTED value="<?php echo $dstore->id?>">
      <?php echo $dstore->name ?>
    </option>
    <?php
        }else {
            ?>
      <option value="<?php echo $dstore->id?>">
        <?php echo $dstore->name ?>
      </option>
      <?php
        }
    }
    ?>
</select>

,

我试图在我的评论中解释这个问题,但是也许在这里更容易看到。

  • 您的页面加载初始表单中包含许多输入内容,包括一些poster_idsposter_qty

  • 如果您提交该表单,则通过单击“提交”按钮,会发生通过POST提交标准HTML表单的情况。页面加载时表单中存在的所有输入将在请求中发送,您的PHP将获得所有输入。

  • 但是,如果您不提交表单,而是更改所选的#banner_store_id选项,则将使用某些Javascript。 JS会做一些事情:

    • 创建一个空的formData对象,忽略当前表单中的所有内容;

    • 向该formData

    • 添加2个新的键/值对
    • 将这两个值发布到您的PHP中。请注意,这不是一种标准的HTML POST,就像您单击“提交”时发生的那样,它是AJAX POST。它本质上独立于页面上的<form>,并且仅当您专门添加它们时才会从表单中过帐字段。您拥有的代码无法执行此操作,因此不包含您​​现有的任何表单字段

    • 如果您尝试在接收此JS POST的PHP中使用$_POST['poster_ids'],它将失败,因为这些字段不在请求中。仅有的东西是poster_idaction

如果您要做,希望在更改#banner_store_id时将表单中的所有字段包含在通过JS发布的数据中,则需要使用表单创建formData本身,as shown in the docs

let myForm = document.getElementById('formtest1');
let formData = new FormData(myForm);

如果执行此操作,那么表单上的所有输入都将捆绑并包含在该formData中,就像普通的POST一样,都将全部发送到您的PHP。

这是您代码的相关部分,已发表评论以进一步解释:

function changebanner(e) {
    // Create a new FormData object - **NOTE** it is empty!  You have not passed
    // in your existing form,so none of the form inputs already on the page are
    // in FormData.  If you POSTed it right away $_POST would be completely empty.
    let formData = new FormData();

    // Now add 2 items to it
    formData.append('poster_id',value);
    formData.append('action','get_poster');

    // Now make your POST,and send formData,which has just those 2 items
    let xhr = new XMLHttpRequest();
    xhr.open("POST","/admin/admin-post.php");
    xhr.send(formData);

    // The POST is done,you sent poster_id and action and nothing else to your PHP
}
本文链接:https://www.f2er.com/3169000.html

大家都在问