Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form echoed with PHP not submitting using ajax

Tags:

ajax

php

I have a form that is echoed out from the database, but the issue is that when I try to submit, only the first echoed form submits and the rest doesn't. Below is my code.

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;
});
});

Just added the code for 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";
    }
}
}
?>

But the ajax seems to only work for the first echoed data and doesn't seem to submit the rest. How do I solve this?

Thanks in advance.

like image 390
diagold Avatar asked Jun 01 '18 12:06

diagold


3 Answers

Add class dynamic-form to form tag and remove id from all fields:

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>';

Update in 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;
    });
});
like image 170
Lovepreet Singh Avatar answered Nov 01 '22 09:11

Lovepreet Singh


Here is solution of your problem :-

$('.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();                  
    });
like image 4
Sanjay Kumar Avatar answered Nov 01 '22 10:11

Sanjay Kumar


It seems everyone here gave you almost the same answer, but it does not entirely satisfy your problem.

To give you the simplest answers:

  • What you are doing is bad practice by principle, because you should not echo "forms"
  • Each form on the page has the same information besides the inputs, which is wrong.

The correct solution:

  • Start using ajax post only for this purpose
  • Don't use FORM, instead just create a div for each question and have the inputs there with the question id
  • Use a modal to edit the questions, that way when you close the modal you reset the inputs in the modal, giving you the ability to edit again a question and save it.

The solution you want right now:

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>

This code is untested, as I do not have your database or any information about the questions you store, however I am 90% positive that if you use this method it will work for you better than any other answer.

If I made some small typo or mistake, the code is very easy to edit and fix it.

FINAL NOTE: "updatequestion.php" is not the problem here, was never the problem.

Good luck!

like image 2
Mecanik Avatar answered Nov 01 '22 08:11

Mecanik