javascript - 在 while 循环中从一种表单发布数据

标签 javascript php jquery html

我正在尝试使用 jQuery 加载在 while 循环内将 PHP 中单个表单的数据发布到另一个页面。目前,当我查看输出时,仅提交第一个结果。当我单击其余表单时,它会不断刷新页面。如何使所有表单都能从我的 PHP 页面发布唯一数据?

这是我的 PHP 脚本:

while (mysqli_stmt_fetch($select_product)): ?>
<div class="col-md-4 top_brand_left" style="margin-top:40px;">

  <div class="hover14 column">
    <div class="tm_top_brand_left_grid">
      <div class="tm_top_brand_left_grid_pos">
      </div>
      <div class="tm_top_brand_left_grid1">
        <figure>
          <div class="snipcart-item block">
            <div class="snipcart-thumb">
              <a href="javascript:void(0)"><img class="lazy" title="" alt="" src="/web/images/spinner.gif" data-original="/web/images/<?php echo $product_image; ?>"></a>
              <p><?php echo htmlentities($product_name); ?></p>
              <h4><?php echo "&#8358;".$product_price; ?><span></span></h4>
            </div>
            <div class="snipcart-details top_brand_home_details">
              <form id="addToCart" method="post">
                <fieldset>
                  <input type="hidden" name="id" id="id" value="<?php echo htmlentities($product_id); ?>">
                  <input type="submit" id="add_to_cart" name="add_to_cart" value="Add to cart" class="button">
                </fieldset>
              </form>
            </div>
          </div>
        </figure>
      </div>
    </div>
  </div>
</div>
<?php endwhile; ?>

这是我的 jQuery 脚本:

$("#addToCart").submit(function(event){
  event.preventDefault();

  var page = $("#page").val();
  var id = $("#id").val();
  var cat_id = $("#cat_id").val();
  var res_name = $("#res_name").val();
  var add_to_cart = $("#add_to_cart").val();

  $("#feedback").load("/web/cart.php", {

    page:page,
    id: id,
    cat_id: cat_id,
    res_name: res_name,
    add_to_cart: add_to_cart

  });
});

最佳答案

更改 PHP 循环中类的所有 id。

然后单击,查找最接近的 .column 以查找相关元素。

$(".addToCart").submit(function(event){
  event.preventDefault();

  var column = $(this).closest(".column");

  var page = column.find(".page").val();
  var id = column.find(".id").val();
  var cat_id = column.find(".cat_id").val();
  var res_name = column.find(".res_name").val();
  var add_to_cart = $(this).val();

  $("#feedback").load("/web/cart.php", {  // This element is outside the PHP loop and has a unique id.

    page:page,
    id: id,
    cat_id: cat_id,
    res_name: res_name,
    add_to_cart: add_to_cart

  });
});

关于javascript - 在 while 循环中从一种表单发布数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51574682/

相关文章:

javascript - 当用 Backbone.js 替换时,queryui 复选框按钮的内容会增加

php - 在共享主机面板中通过 htaccess 从文件夹创建虚拟子域

jquery - 谷歌机器人看到了什么?生成代码还是源代码?

jquery - 如何将数据插入 xml 文件

javascript - Cypress img 元素属性检查

Javascript日期对象在从日期字符串创建时自动添加一天

php - 基于 Laravel 的条件注册重定向

javascript - 使用 AngularJS 和 PHP 发送电子邮件

Javascript:从动态创建的实例调用嵌套函数

javascript - 我可以使用字典作为矩形的 'data' 对象吗?