javascript - 在 ajax 调用中向每个表单输入添加单个隐藏输入值

标签 javascript jquery arrays ajax

我有一个带有按钮的表单,可以添加动态输入字段,它会产生 ajax 问题。我的 ajax 帖子给了我 500 个错误 但我现在的数据控制台日志是这样的: enter image description here

但我需要将它们插入为

insert into ticker_content (ticker_id, content)
     values (1, 'one'), (1, 'two');

如果这是有道理的。

所以基本上,问题是我在任何给定时间都有多个输入(包含文本值),并且表单中的隐藏输入为我提供了正确的股票代码 ID。

但是,我需要使数组包含每个元素都具有输入文本值和股票代码 ID 的元素。因此,对于创建和填充的每个输入,我还需要将该表单的隐藏输入的值分配给它,以便我可以将它们成对发送到我的 foreach 循环并插入。

这是我为插入而调用的 addticker.php:

$items = $_POST['Items'];
$tickerID = $_POST['tickerID'];

foreach ($items as $item){

    $addTicker = "
        INSERT INTO ticker_content (tickerID, content)
        values ('$tickerID', '$item');
     "
     $mysqlConn->query($addTicker);
}

所以基本上对于每个 Items[] 值,我需要插入相同的隐藏字段。

这是我的表单和JS代码供引用。第一个JS block 主要是动态添加输入的功能,但最后一个JS block 是使用serializeArray()的ajax;

<?php foreach($tickerDisplays as $key => $ticker):?>

    <form id="Items" method="post">   
        <label id="ItemLabel">Item 1: </label>
        <input type="text" name="Items[]"><br/> <!--form starts with one input-->
        <button type="button" class="moreItems_add">+</button> <!--button dynamically adds input, up to 10 per form-->

        <input type="hidden" name="tickerID" id="tickerID" class="tickerIdClass" value="<?php echo $ticker['ticker'] ?>"><!--hidden input used for tickerID-->
        <input type="submit" name="saveTickerItems" value="Save Ticker Items">  <!--submit button-->
    </form>

<?php endforeach;?>




<!-- This is the functionality for each form to click the '+' button and create new inputs -->
<script type="text/javascript">

$("button.moreItems_add").on("click", function(e) {
var tickerID = $(this).closest('form').find('.tickerIdClass').val(); //get value of hidden input for form
  var numItems = $("input[type='text']", $(this).closest("form")).length;
  if (numItems < 10) {
    var html = '<label class="ItemLabel">Item ' + (numItems + 1) + ': </label>';
    html += '<input type="text" name="Items[]"/><br/>';
    $(this).before(html);
    console.log(tickerID);
  }
});

</script>

<!-- This is the ajax call to send all filled out and created inputs from form along with the hidden input -->
<script type="text/javascript">
$("#Items").submit(function(e) {
    e.preventDefault();
    var data = $("#Items").serializeArray();
    console.log(data);

$.ajax({
       type: "POST",
       url: "addticker.php",
       data: $("#Items").serializeArray(), // serializes the form's elements.
       success: function(data)
       {
           alert(data); // show response from the php script.
       }
     });

});

</script> 

最佳答案

首先,您的代码中缺少一个分号(这可能会导致 500 错误)。

其次,如果您想将表单中的所有字段捆绑为单个查询,则以下内容将构建一个类似于您之前在问题中提到的查询:

INSERT INTO ticker_content (ticker_id, content) VALUES(1, 'one'), (1, 'two'), ...

$items = $_POST['Items'];
$tickerID = $_POST['tickerID'];

$addTicker = "INSERT INTO ticker_content (tickerID, content) values";
foreach ($items as $item){
    $addTicker .= "('$tickerID', '$item'),";
}
$addTicker = substr($addTicker, 0, -1); // Eat that last comma

$mysqlConn->query($addTicker);

您的 HTML 还需要一些工作,因为 id 属性在页面上应该是唯一的。由于您要复制表单,因此您应该执行如下操作:

<form id="Items<?php echo $ticker['ticker']?>" class="tickerform" method="post">   

然后更新您的 JavaScript:

// Using $(this) in Jquery allows you to access the 
// element that is making the method call (in this case, the form)
$(".tickerform").submit(function(e) {
    e.preventDefault();
    var data = $(this).serializeArray(); 
    console.log(data);
    $.ajax({
       type: "POST",
       url: "addticker.php",
       data: data, // Don't need to serialize again, 'var data' is still in scope.
       success: function(data)
       {
           alert(data); // show response from the php script.
       }
    });
});

关于javascript - 在 ajax 调用中向每个表单输入添加单个隐藏输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52319718/

相关文章:

javascript - 快速重复 ajax 过程是否有危险?

jquery - 删除先前附加的文本

arrays - 在哈希数组中添加相同键的值

javascript - 检测图像何时滚出 View

c - 更新的命令行参数

javascript - TypeError : result. 推送不起作用

javascript - 如何在字符串中搜索字符串数组中包含的所有值? (JavaScript)

javascript - CKEditor:使字体大小组合框可编辑或使用新控件

javascript - 如何在 ng-view 中使用 ng-view?

php - 无限滚动for循环 block