【问题标题】:Loop through submit buttons and post to MySQL w/ ajax循环提交按钮并使用 ajax 发布到 MySQL
【发布时间】:2016-09-27 05:27:05
【问题描述】:

我目前有一个根据数据库中的行数创建的表单。每行都被拉入其自己的数据可编辑的形式。每行也有自己的按钮。

$i = 0; 
  while($row = mysql_fetch_array( $result )) { 
    if ($row['stage']=='1'){ $i++; 
<form method="post" name="form<?php echo $i;?>' id='form<?php echo $i;?>">
<input type="text" name="product<?php echo $i;?>" value="<?php echo $row['product'];?>" id="product<?php echo $i;?>" />
<input type='button' name='submit<?php echo $i;?>' value='NEXT'/> 
</form>

JQUERY

$(".submit1").click(function(){
        $.ajax({
            type: "post",
            url: "xx1.php",
            data: $("#form1").serialize(),
            success: function() {
                alert("UPDATE SUCCESS");
                location.reload();  
            },
            error: function () {
                alert("FAILED");
            }
        });
    });

xx1.php

$ProductOne= strip_tags($_POST['product1']);
 if ($StageOne == "1"){
        SQL STATEMENT
   }elseif ($StageOne == "2"){
         SQL STATEMENT
     }elseif ($StageOne == "3"){

我目前每行都有 xx.php (xx1.php,xx2.php,xx3.php),在我的 php 文件中我的 $_POST['x'] 匹配 xx.php ($_POST['product1' ], $_POST['product2'], $_POST['product3']

如果单击 submitx 时如何编写更新 i = i 的行(单击 submit1 时更新 product1,单击 submit2 时更新 product2)

【问题讨论】:

    标签: php jquery mysql ajax


    【解决方案1】:

    您需要获取按钮 id(被点击的那个)并调用相应的文件来执行。

    $("button").click(function() {
      //extract the name of the button clicked
      var name = $(this).attr('name');
      //get the button id from name.
      var buttonId = name.split('submit')[1];
      $.ajax({
          type: "post",
          url: "xx.php",
          data: $("#form" + buttonId + "").serialize(),
          success: function() {
              alert("UPDATE SUCCESS");
              location.reload();  
          },
          error: function () {
             alert("FAILED");
          }
      });
    });
    

    发送到 xx.php 的数据有 id。所以你可以用这个id对xx.php进行操作。

    $id = //get the id from form data sent from js
    $Product = strip_tags($_POST["product{$id}"]);
    .
    .
    //use id instead of number in further operations.
    

    【讨论】:

    • 感谢您的及时回复。这对按钮有意义。如果我不想手动创建每个 xx.php (xx1,xx2) 并且我只想要一个脚本来更新单击按钮的行,这将如何工作?
    • @Billy 仅调用 xx.php 并将 id 发送到文件。检查更新的答案
    猜你喜欢
    • 2013-04-09
    • 2012-11-30
    • 2014-03-28
    • 2021-10-26
    • 2018-03-19
    • 1970-01-01
    • 2012-02-10
    • 1970-01-01
    • 2015-09-25
    相关资源
    最近更新 更多