使用PHP与ajax进行表单提交无响应

10

我有一个表格,是从数据库中echo出来的。但问题是,当我尝试提交时,只有第一个echo出来的表格提交了,其余的都没有。以下是我的代码。

editquestion.phh

<thead>
          <tr>
            <th style="width: 5%;">S/N</th>
            <th style="width: 20%;">QUESTION</th>
            <th style="width: 40%;">ANSWER</th>
            <th style="width: 30%;">KEYWORDS</th>
            <th style="width: 5%;">SAVE/UPDATE</th>
            </tr>
      </thead>
      <tbody>
        <?php
        $sql = $db->prepare("SELECT * FROM questions");
        $result = $sql->execute();

        while ($row = $result->fetchArray(SQLITE3_ASSOC))
        {
            $quiz_id = $row['quiz_id'];
            $question = $row['question'];
            $answer = $row['answer'];
            $keywords = $row['keywords'];

            echo '<form action="updatequestion.php" method="post" enctype="multipart/form-data">
            <tr>
            <td><input style="width: 50%" type="text" name="cid" id="cid" value="'.$quiz_id.'"></td>
            <td><input type="text" name="question" id="question" value="'.$question.'"></td>
            <td><input type="text" name="answer" id="answer" value="'.$answer.'"></td>
            <td><input type="text" name="keywords" id="keywords" value="'.$keywords.'"></td>
            <td><input type="submit" name="qupdate" class="qupdate" value="Update"></td>
            </tr>
            </form>';

        }
        ?>
        </tbody>
  </table>

qupdate.js

$(document).ready(function() {
$('.qupdate').click(function() {
    question = $('#question').val();
    answer = $('#answer').val();
    keywords = $('#keywords').val();
    id = $('#cid').val();

    $.ajax({
        type: "POST",
        url: "updatequestion.php",
        data: "cid="+id+"&question="+question+"&answer="+answer+"&keywords="+keywords,
        success: function(html){
            if(html = "true")
            {
                $('.qupdate').css("opacity", "1");
            }
            else
            {
                alert("not successful");
            }
        },
        beforeSend: function(){
            $('.qupdate').css("opacity", "0.5");
        }
    });
    return false;
});
});

刚刚添加了 updatequestion.php 的代码。

<?php
session_start();
require_once("db.php");
$db = new MyDB();


if (isset($_POST['question']) || isset($_POST['answer']) || isset($_POST['cid']))
{
$id = strip_tags(@$_POST['cid']);
$cname = strip_tags(@$_POST['question']);
$cunit = strip_tags(@$_POST['answer']);
$keywords = strip_tags(@$_POST['keywords']);

if (empty($cname) || empty($cunit))
{
    echo "fill";
}
else
{
    $sql = $db->prepare("UPDATE questions SET question = ?, answer = ?, keywords = ? WHERE quiz_id = ?");
    $sql->bindParam(1, $cname, SQLITE3_TEXT);
    $sql->bindParam(2, $cunit, SQLITE3_TEXT);
    $sql->bindParam(3, $keywords, SQLITE3_TEXT);
    $sql->bindParam(4, $id, SQLITE3_INTEGER);

    $result = $sql->execute();

    if ($result)
    {
        echo "true";
    }
    else
    {
        echo "false";
    }
}
}
?>

但是ajax似乎只能处理第一个回显数据,并且似乎无法提交其余数据。我该如何解决这个问题?

提前致谢。


1
你有几个具有相同id的元素,这是不起作用的,因为id需要是唯一的。所以js选择第一个(另一个浏览器可能会选择最后一个...) - Jeff
你想要更新所有的回应问题吗?那么表单标签和提交按钮应该在循环之外,并且输入标签的名称应该设置为 name="cid[]",这样它就会发送数组。看一下这个链接:https://dev59.com/CHA75IYBdhLWcg3wZ4Nr - Baim Wrong
你打算一次性提交所有内容还是只提交用户提交的那一行? - Tarun Lalwani
只有一行,谢谢。 - diagold
每行具有相同的形式,在每个表单中所有输入的name和id属性都是相同的,这实际上是错误的,并且是问题的根本原因。 - Karan Thakkar
显示剩余2条评论
6个回答

5
在表单标签上添加类名dynamic-form,并从所有字段中删除id:
echo '<form class="dynamic-form"  action="updatequestion.php" method="post" enctype="multipart/form-data">
            <tr>
            <td><input style="width: 50%" type="text" name="cid" value="'.$quiz_id.'"></td>
            <td><input type="text" name="question" value="'.$question.'"></td>
            <td><input type="text" name="answer" value="'.$answer.'"></td>
            <td><input type="text" name="keywords" value="'.$keywords.'"></td>
            <td><input type="submit" name="qupdate" class="qupdate" value="Update"></td>
            </tr>
            </form>';

JS中的更新

$(document).ready(function () {
    $('.dynamic-form').on('submit', function () {
        var formdata = $(this).serialize();
        $.ajax({
            type: "POST",
            url: "updatequestion.php",
            data: formdata,
            success: function (html) {
                //success
            }
        });
        return false;
    });
});

4
以下是您问题的解决方案:
$('.qupdate').click(function() {   
        var question = $(this).closest("form").find('input[name=question]').val();      
        var answer = $(this).closest("form").find('input[name=answer]').val();
       var keywords = $(this).closest("form").find('input[name=keywords]').val();
       var id = $(this).closest("form").find('input[name=cid]').val();                  
    });

这将返回父表单输入值。其余代码按照通常方式工作。 - Sanjay Kumar
我用 @SanjayKumar 编写的代码替换了所有这些 question = $('#question').val(); answer = $('#answer').val(); keywords = $('#keywords').val(); id = $('#cid').val();,但仍然无法正常工作,或者我使用方法不正确? - diagold
你能分享一些细节吗? - Sanjay Kumar
尝试使用console.log输出值。 - Sanjay Kumar
我刚刚更新了我的问题,展示了 updatequestion.php 的代码,如果问题是从那里引起的。 - diagold
显示剩余2条评论

2
似乎这里的每个人都几乎给出了相同的答案,但它并不能完全满足您的问题。
为了给您最简单的答案:
- 从原则上讲,您所做的是不好的实践,因为您不应该回显"表单" - 页面上的每个表格除了输入框以外都有相同的信息,这是错误的。
正确的解决方案:
- 只使用 AJAX 提交。 - 不要使用表单,而是为每个问题创建一个 DIV 并在那里添加带有问题 ID 的输入框。 - 使用模态框编辑问题,在关闭模态框时重置模态框中的输入框,使您能够再次编辑问题并保存它。
您现在想要的解决方案是:
editquestion.php
        <thead>
              <tr>
                <th style="width: 5%;">S/N</th>
                <th style="width: 20%;">QUESTION</th>
                <th style="width: 40%;">ANSWER</th>
                <th style="width: 30%;">KEYWORDS</th>
                <th style="width: 5%;">SAVE/UPDATE</th>
                </tr>
          </thead>
          <tbody>
            <?php
            $sql = $db->prepare("SELECT * FROM questions");
            $result = $sql->execute();

            while ($row = $result->fetchArray(SQLITE3_ASSOC))
            {
                $quiz_id = $row['quiz_id'];
                $question = $row['question'];
                $answer = $row['answer'];
                $keywords = $row['keywords'];

                echo '<tr>';
                    echo '<td><input style="width: 50%" type="text" name="cid" id="cid" value="'.$quiz_id.'"></td>';
                    echo '<td><input type="text" name="question" id="question" value="'.$question.'"></td>';
                    echo '<td><input type="text" name="answer" id="answer" value="'.$answer.'"></td>';
                    echo '<td><input type="text" name="keywords" id="keywords" value="'.$keywords.'"></td>';
                    echo '<td><input type="button" name="qupdate" class="qupdate" value="Update" onclick="doEdit('.$quiz_id.');"></td>';
                echo '</tr>';
            }
            ?>
        </tbody>
     </table>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Edit Question</h4>
      </div>
      <div class="modal-body">
        <p>Edit your question:</p>
        <p><input type="hidden" id="question_id" id="question_id" value=""></p>
        <p><input type="text" id="question_text" value=""></p>
        <p><input type="text" id="question_answer" value=""></p>
        <p><input type="text" id="question_keywords" value=""></p>

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" id="doupdate" class="btn btn-default">Update Question</button>
      </div>
    </div>

  </div>
</div>

qupdate.js:

<script>
$(document).ready(function() {

    function doEdit(question_id) {
        /** POPULATE THE MODAL WITH THE QUESTION DATA **/
        $.ajax({
                type: "POST",
                url: "getquestiondata.php", /** create this file, and return the question data from the database based on the "cid" **/
                data: "cid="+question_id+",
                success: function(response){

                        $('#question_id').val(response.cid);
                        $('#question_text').val(response.text);
                        $('#question_answer').val(response.answer);
                        $('#question_keywords').val(response.keywords);
                }
        });
    }

    /** DO THE ACTUAL UPDATE **/
    $('#doupdate').click(function() {

        var question_id = $('#question_id').val();
        var question_text = $('#question_text').val();
        var question_answer = $('#question_answer').val(),
        var question_keywords = $('#question_keywords').val(),

        $.ajax({
            type: "POST",
            url: "updatequestion.php",
            data: "cid="+question_id+"&question="+question_text+"&answer="+question_answer+"&keywords="+question_keywords,
            success: function(html){
                if(html = "true")
                {
                    $('.qupdate').css("opacity", "1");

                    $('#myModal').modal('toggle');

                    // Reset the modal inputs
                    $('#question_id').val("");
                    $('#question_text').val("");
                    $('#question_answer').val("");
                    $('#question_keywords').val("");

                }
                else
                {
                    alert("not successful");
                }
            },
            beforeSend: function(){
                $('.qupdate').css("opacity", "0.5");
            }
        });
        return false;
    });
});
</script>

这段代码未经测试,因为我没有你的数据库或任何关于你存储的问题的信息,但是我90%的确信如果你使用这种方法,它将比任何其他答案更好地为你工作。

如果我犯了一些小错别字或错误,那么这段代码非常容易编辑和修复。

最后注意:"updatequestion.php"不是问题所在,从来都不是问题。

祝你好运!


1

我尝试使用Sanjay Kumar的答案来帮助你,因为你想要每行保存。

editquestion.php

<thead>
    <tr>
        <th style="width: 5%;">S/N</th>
        <th style="width: 20%;">QUESTION</th>
        <th style="width: 40%;">ANSWER</th>
        <th style="width: 30%;">KEYWORDS</th>
        <th style="width: 5%;">SAVE/UPDATE</th>
    </tr>
</thead>
<tbody>
<?php
    // assuming your database already connected here
    $sql = $db->prepare("SELECT * FROM questions");
    $result = $sql->execute();

    while($row = $result->fetchArray(SQLITE3_ASSOC))
    {
        $quiz_id = $row['quiz_id'];
        $question = $row['question'];
        $answer = $row['answer'];
        $keywords = $row['keywords'];

        // enctype="multipart/form-data" is used if the form contains a file upload, and echo per line for clarity
        echo '<form action="updatequestion.php" method="post">';
        echo '<tr>';
        echo '<td><input style="width: 50%" type="text" name="cid" value="'.$quiz_id.'"></td>';
        echo '<td><input type="text" name="question" value="'.$question.'"></td>';
        echo '<td><input type="text" name="answer" value="'.$answer.'"></td>';
        echo '<td><input type="text" name="keywords" value="'.$keywords.'"></td>';
        echo '<td><input type="submit" name="qupdate" class="qupdate" value="Update"></td>';
        echo '</tr>';
        echo '</form>';
    }
    ?>
    </tbody>
</table>

qupdate.js

// assuming you already loaded jquery library
$(document).ready(function()
{
    $('.qupdate').click(function()
    {
        var id = $(this).closest("form").find('input[name=cid]').val(); 
        var question = $(this).closest("form").find('input[name=question]').val();      
        var answer = $(this).closest("form").find('input[name=answer]').val();
        var keywords = $(this).closest("form").find('input[name=keywords]').val();

        var postData = {'cid' : id, 'question' : question, 'answer' : answer, 'keywords' : keywords};

        $.ajax(
        {
            type: "POST",
            url: "updatequestion.php",
            data: postData,
            success: function(response)
            {
                // note the '==' operator
                if(response == "true")
                {
                    $('.qupdate').css("opacity", "1");
                }
                else
                {
                    console.log(response);
                    alert("not successful");
                }
            },
            error: function(e)
            {
                console.log(e);
            },
            beforeSend: function()
            {
                $('.qupdate').css("opacity", "0.5");
            }
        });
        return false;
    });
});

updatequestion.php

<?php
    session_start();
    require_once("db.php");
    $db = new MyDB();

    if(isset($_POST['cid']) && isset($_POST['question']) && isset($_POST['answer']) && isset($_POST['keywords']))
    {
        $id = filter_input(INPUT_POST, 'cid', FILTER_SANITIZE_STRING);
        $cname = filter_input(INPUT_POST, 'question', FILTER_SANITIZE_STRING)
        $cunit = filter_input(INPUT_POST, 'answer', FILTER_SANITIZE_STRING)
        $keywords = filter_input(INPUT_POST, 'keywords', FILTER_SANITIZE_STRING)

        if($id == '' || $cname == '' || $cunit == '' || $keywords == '')
        {
            echo "one or more parameter is empty";
        }
        else
        {
            $sql = $db->prepare("UPDATE questions SET question = ?, answer = ?, keywords = ? WHERE quiz_id = ?");
            $sql->bindParam(1, $cname, SQLITE3_TEXT);
            $sql->bindParam(2, $cunit, SQLITE3_TEXT);
            $sql->bindParam(3, $keywords, SQLITE3_TEXT);
            $sql->bindParam(4, $id, SQLITE3_INTEGER);

            $result = $sql->execute();

            if ($result)
            {
                echo "true";
            }
            else
            {
                echo "false";
            }
        }
    }
    else
    {
        echo "wrong parameter";
    }
?>

我在代码中添加了一些注释。
如果某些内容无法正常工作,您可以检查元素并在控制台选项卡中查看其他消息。我添加了过滤输入函数以增强安全性,并更改了空变量的比较方式。
希望这能给您一些想法。

1

你可以尝试其他方式,也许会起作用

$(document).on('click','.qupdate',function() {   
        var question = $(this).closest("form").find('input[name=question]').val();      
        var answer = $(this).closest("form").find('input[name=answer]').val();
       var keywords = $(this).closest("form").find('input[name=keywords]').val();
       var id = $(this).closest("form").find('input[name=cid]').val();                  
    });

//或者

jQuery('body').on('click', '.qupdate', function (){
    var form = $(this).closest("form");
    var forminput = form.serialize();
});

1
正如其他人提到的那样,ID应该在页面上是唯一的。在您的情况下,您可以获取整个表单并序列化其数据:
$(document).ready(function() {
    $('.qupdate').click(function() {
        // Clicked $('.qupdate') is now $(this)
        // But we should define $this variable if we want to be able to use it in callbacks.
        // This is more efficient way instead of searching for $('.qupdate') in DOM again and again.
        // Unless you want to set CSS for ALL .qupdate buttons in ALL forms.
        var $this = $(this);

        $.ajax({
            type: "POST",
            url: "updatequestion.php",
            // find closest to .qupdate form and serialize it's data
            data: $this.closest('form').serialize(),
            success: function(html) {
                // use double (or even tripple) equals operator if you want to compare, otherwise you'll just set html as "true"
                // and it'll be always successful
                if(html == "true") {
                    // We use $this variable here which we've defined earlier, and which, as we remember,
                    // stands for clicked $('.qupdate') button
                    $this.css("opacity", "1");
                } else {
                    alert("not successful");
                }
            },
            beforeSend: function() {
                // We use $this variable here which we've defined earlier, and which, as we remember,
                // stands for clicked $('.qupdate') button
                $this.css("opacity", "0.5");
            }
        });
        return false;
    });
});

更新

也许你发送的响应并不完全是“true”或“false”? 为了确保您不发送任何额外字符,您应该在echo之后调用exit:

if ($result)
{
    echo "true";
    exit;
}
else
{
    echo "false";
    exit;
}

如果您不确定,可以直接从JS中删除此HTML检查,因为实际上它在您的示例中从未起作用。
// remove this if-else block
if(html = "true")
{
    $('.qupdate').css("opacity", "1");
}
else
{
    alert("not successful");
}

你也可以使用浏览器开发工具来检查所发送和接收的内容。例如,在Chrome中按F12,在打开的面板中选择“网络”选项卡。现在点击任何表格中的按钮,你会看到新请求已发送。等待它完成——状态列应该接收到一些数字(如果一切正常,则为200)。现在你可以点击此请求并查看详细信息。甚至有视频示例=) https://www.youtube.com/watch?v=WOQDrGrd9H8

我没有成功。 - diagold
那么可能HTML并不是“真的”?在updatequestion.php中你返回什么?如果您发布updatequestion.php的代码,可能会有所帮助。 - Djengobarm
我编辑了我的回答,请查看“更新”标题后的部分。 - Djengobarm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接