【问题标题】:How can I edit data in modal and save it to the database?如何在模态中编辑数据并将其保存到数据库中?
【发布时间】:2019-08-05 12:56:33
【问题描述】:

我正在建立一个学校数据库网站,我想添加一个“编辑”按钮。我想在模态框中编辑和保存元素。我写了一些代码,第一步(即当你点击元素模态框时)正在工作。 但是在模式框中我看不到被点击的元素,当我点击编辑按钮时,被点击元素的内容被删除。如何在模态框中调用单击的元素? 另外,你能解释一下如何在编辑后保存它吗?非常感谢。


$(document).ready(function () {


    //// CHECK INPUT FIELD: Not empty
    notEmpty();

    /* START: Get List on Pageload */
    function getList() {
        var data = {'action': 'getList'};
        $.ajax({
            url: 'Controller/CourseController.php',
            data: data, // action = getList muss dem Controller ,
            type: 'post',
            success: function (data) {
                $('#lecture-result').html(data);
                //ajax is finished!
            }
        });
    }
    /* END: Get List on Pageload*/

    // Also cut leading and trailing whitespace
    $('body').on('keydown', '.lecture-name-field', function (e) {
        console.log();
        if (e.which === 32 && e.target.selectionStart === 0) {
            return false;
        }
    });

    /* START: Add a new Lecture */
    $('body').on('submit', '#add-lecture-form', function (e) {
        e.preventDefault();

        //// CHECK INPUT FIELD: Not empty
        notEmpty();

        var postData = $(this).serialize();
        var url = $(this).attr('action');
        var type = $(this).attr('method');
        $.ajax({
            url: url,
            data: postData,
            type: type,
            success: function (data) {
                $("#lecture-result").html(data);
                console.log('new lecture added');
            }
        });
        //clean the input field after click
        $('#add-lecture-form')[0].reset();

    });
    /* END: Add a new Lecture */

    function notEmpty() {

        $('#save').attr('disabled', 'disabled');
        $('.lecture-name-field').keyup(function () {
            if ($(this).val() !== '') {
                $('#save').removeAttr('disabled');
            } else {
                $('#save').attr('disabled', 'disabled');
            }
        });
    }

    /* Handle Click on action Buttons
     * This is used for Actions:
     * - delete
     * - edit
     * */
    $("body").on('click', '.action-button', function (e) {
        e.preventDefault();
        var action = $(this).data('action');

        // if action == edit



        // validate Input

          save();
          input ();

        var data = {'action': action};
        var url = $(this).attr('href');
        var id = $(this).data('id');

        $.ajax({
            url: url,
            type: 'POST',
            cache: false,
            data: {
                'action': action,
                'id': id
            },
            success: function (data) { //we want to see this data as result it will appeare as result
                if (!data.error) {
                    $('#lecture-result').html(data); //data from above

                }
            }
        });

    });

function input() {

    $('#edit').on('click', function () {
        var url = $(this).attr('href');
        var text = $('.autofiller');
        $.ajax({
            url: url,
            method: "GET",
            data: {
                'id': text

            },
            success: function (data) {
                var name = JSON.parse(data);
                $(".autofiller").val(name.name);// Try this 
            }

        });
     });
    }

    function save() {


        $('#btnSave').on('click', function (event) {
            alert("save button clicked");
            event.preventDefault();

        });

    }

    /* Initial Function Calls: */
    getList();
});

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Edit Lecture</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">..... </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
            </div>
        </div>
    </div>
</div> 
   <div class="row">

                    <form method="post" id="add-lecture-form" class="col-xs-6 ajax-form" action="Controller/CourseController.php">
                        <div class="form-group">
                            <input type="text" name="title" class="form-control lecture-name-field" placeholder="Please enter a lecture name!!">
                        </div>
                        <input type="hidden" id="action" name="action" value="create">
                        <div class="form-group">
                            <input type="submit" id="save" class="btn btn-success" value="add a lecture">
                        </div>
                    </form>

                    <div class="col-xs-6">  </div>

                    <div id="lecture-result"></div>


                </div>
            </div>      




function getCourseListAsView() {

    $dbConfigObject = new DbConfig;
    $dbConnection = $dbConfigObject->getDBConnection();

    $query = "SELECT * FROM courses";
    $search_query = mysqli_query($dbConnection, $query);

    $listview = "<ul class='course-list'>";

    while ($row = mysqli_fetch_array($search_query)) {
        //title column in db
        $listview .= '<li class="course-list-element">'
                . '<a class="detail-link" data-id="' . $row['id'] . '" href="/CourseController">' . $row['title'] . '</a>'
                . '<button type="button" id="edit" data-toggle="modal" data-target="#myModal" class="btn btn-primary action-button" data-id="' . $row['id'] . '" data-action="edit" href="Controller/CourseController.php">edit</button>'
                . '<button type="button" class="btn btn-danger action-button" data-id="' . $row['id'] . '" data-action="delete" href="Controller/CourseController.php">delete</button>'
                . '</li>';
    }
    $listview .= "</ul>";

    echo $listview;
}

function deleteCourse($id) {

    $dbConfigObject = new DbConfig;
    $dbConnection = $dbConfigObject->getDBConnection();

    /** @var type $id */
    /** @var type $query */
    $query = "DELETE FROM courses WHERE id = $id";
    /** @var type $query_delete_lecture */
    $query_delete_lecture = mysqli_query($dbConnection, $query);
    if (!$query_delete_lecture) {
        die('QUERY FAILED');
    }
}

function editCourse($id) {

    $dbConfigObject = new DbConfig;
    $dbConnection = $dbConfigObject->getDBConnection();


    /** @var type $title */
    if ($dbConnection->connect_error) {
        die("Connection failed: " . $dbConfigObject->connect_error);
    }

    $query = "UPDATE courses set title='Math' where id=$id";

    if ($dbConnection->query($query) === TRUE) {
        echo "Record updated successfully";
    } else {
        echo "Error updating record: " . $dbConnection->error;
    }

    $dbConnection->close();
}
}

【问题讨论】:

  • 你能在点击和模态打开的地方显示你的 html,以及你需要在模态中显示的内容吗?
  • 我已经添加了我的html。我想在我的模态框单击元素上显示。(我有一个输入框,我可以将一些数据添加到我的数据库中。添加数据后有两个选项,其中一个是删除(正在工作),另一个是正在编辑(我需要“编辑”的帮助)。谢谢
  • 你的 html 中的action-button 在哪里,提供的jquery 代码是否用于编辑?
  • 操作按钮在我的 php 文件中。 (我已经添加了)。
  • 您在表格中显示&lt;ul&gt;..?你如何显示input type 每一行有不同的input 还是只有你发布的一个,你还需要得到&lt;input type="text" name="title" class="form-control lecture-name-field" placeholder="Please enter a lecture name!!"&gt; 这个输入的值吗?我仍然无法理解您需要获取哪个input

标签: php jquery sql ajax crud


【解决方案1】:

您可以将需要编辑的数据放在您的&lt;button&gt; 中。假设您需要编辑来自数据库的title,即:

<button type="button" id="edit" class="btn btn-primary action-button" data-id="' . $row['id'] . '" data-action="edit" 
 data-value="'.$row['title'].'" href="Controller/CourseController.php">edit</button>
    <!--^added this--> 

现在,点击edit 按钮,您将在jquery 中打开模态,在模态下的input 字段中获取data-value 的标题,即:

您的 jquery 将如下所示:

$('#edit').on('click', function () {
        var url = $(this).attr('href');
        var text = $('.autofiller');
         var title=$(this).attr("data-value");//getting title
         var id=$(this).attr("data-id"); //getting id
          $(".title").val(title); //assiging value of title to your input under modal
            //opening modal
           $("#myModal").modal('show');
          //if save button click
          $(".btn-primary").on("click", function() {
          //getting title if made change
         var new_title=$(".title").val(); 
        $.ajax({
            url: url,
            method: "GET",
            data: {
                'id': id,
                'title':title //<--sending new title

            },
            success: function (data) {
                $('#myModal').modal('hide');//<--hiding modal 
                var name = JSON.parse(data);
                $(".autofiller").val(name.name);// Try this 
            }

        });
     });
  });

只需在您的模式中添加一个输入字段class =title:即:

你的模态:

   <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        ..
            <div class="modal-body">
          <!--added input box to edit data -->
            Title : <input type="title" class="title"/>
              </div>
            ...
        </div>
    </div>
</div>

在您的 php 文件中,只需使用 $_GET 获取您的新标题和 id 并在您的 Update 查询中传递相同的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    • 2023-03-17
    • 2016-03-14
    • 1970-01-01
    • 1970-01-01
    • 2012-06-09
    • 2016-11-26
    相关资源
    最近更新 更多