繁体   English   中英

如何在模态中编辑数据并将其保存到数据库中?

[英]How can I edit data in modal and save it to the database?

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


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

您可以将需要编辑的数据放在<button>假设您需要编辑来自数据库的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查询中传递相同的内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM