Last modified on December 18th, by Vincy.

Modal are the most commonly used popovers to prompt input from the user. Add Edit with modal dialog will minimize design effort. There are various ways to display popovers as pop-up , dialog boxes or overlays. In this tutorial, I have shown dialog boxes for displaying the comment add/edit form.

In this example, I have used a jQuery based library to display modal window. jQuery Dialogify is an easy, lightweight and customizable plugin. Dialogify plugin allows users to include any kind of HTML into a Dialog box. It also supports users to play around with callback events. In a previous tutorial, we have seen about AJAX comments system with an edit delete option.

Add Edit Comments

In this PHP AJAX comments system, the modal windows are used to show the HTML form to add edit comments. jQuery AJAX functions are used to implement the AJAX based comments system in PHP.

There are various ways to display the dialog boxes by using this Dialogify plugin. I have created separate files with the comment add and edit form HTML. While initializing the Dialogify plugin, these filenames are specified to load the HTML form into a dialog window. We have learned how to perform the add edit with a dialog box using jQuery modal window.

Landing HTML with Add Edit Comments Option

This is the landing page that loads the dependent library files and initializes library function to create expected output. On loading this page, the dynamic comment is fetched from the database and displayed in a list with an option to add a new comment. Also, each comment row will have an edit option.  The add and edit controls click event will trigger the Dialogify plugin. If you want a delete option on each comment row you can find an example in the linked article.

<?php
require_once ('db.php');
?>
<!doctype html>
<head>
<script type="text/javascript" src="http://phppot.com/vendor/jquery/jquery-3.2.1.min.js"></script>

<script type="text/javascript" src="vendor/dialogify/dialog-polyfill.js"></script>
<script type="text/javascript" src="vendor/dialogify/dialogify.js"></script>

<script type="text/javascript"
    src="vendor/dialogify/dialogify.min.js?v2"></script>

<script type="text/javascript" src="editRecords.js"></script>

<link rel="stylesheet" type="text/css" ="all"
    href="vendor/dialogify/dialogify.css">
<link rel="stylesheet" type="text/css" ="all" href="style.css">
</head>
<body>

    <h2>Add Edit Comments using jQuery Dialogify</h2>

    <div id="container">
            <?php
            $selectQuery = "SELECT * FROM tbl_comments";
            $result = $conn->query($selectQuery);
            if ($result->num_rows > 0) {
                while ($row = $result->fetch_assoc()) {
                    ?>
                    <div class="comment-row">

            <div id="editFrame">

                <div id="name_val<?php echo $row['id']; ?>">
                                        <?php echo $row['name']; ?>
                                    </div>
                <div id="website_val<?php echo $row['id']; ?>">
                                        <?php echo $row['website']; ?>
                                    </div>

                <div id="content_val<?php echo $row['id']; ?>"
                    class="comment-message">
                                        <?php echo $row['content']; ?>
                                    </div>
                <input type='button' class="btn-edit"
                    id="<?php echo $row['id']; ?>" value="Edit"
                    onclick="edit_row('<?php echo $row['id']; ?>');" />

            </div>
        </div>

                    <?php
                }
            }
            ?>
            <input id="insert_button" type="button" class="btn-submit"
            value="Create a comment" />
    </div>
</body>
</html>

jQuery Script to Call functions to Add Edit Comments

All the jQuery JavaScript are in the editRecords.js file. In this file, it contains the event handlers and also includes the add edit action controllers. In this , the jQuery Dialogify is initialized and loads the corresponding add edit comments form on the click event of the insert or edit controls.

The initialization process requires HTML or source to be loaded in the form of a dialog or modal. Also, it requires the set of options like title, button specification if any. In this example, I have specified setting for two buttons Okay and Cancel. By clicking Okay, the Add Edit comments action will be performed via AJAX.

After performing the successful add or edit action the recently updated comment data will be loaded to the UI. The AJAX callback is the right point at which the code is written to get the AJAX response and update comments UI with the response data.

$(document).ready(function () {
	var options = {
		    ajaxPrefix: ''
		};

    $('#insert_button').click(function () {
    
    		new Dialogify('add-form.php', options)
                .title('Create New Comment')
                .buttons([
                    {
                        text: 'Cancel',
                        click: function (e) {
                            console.log('cancel click');
                            this.close();
                        }
                    },
                    {
                        text: 'Okay',
                        type: Dialogify.BUTTON_PRIMARY,
                        click: function (e) {
                            var name = document.getElementById("username").value;
                            var website = document.getElementById("website").value;
                            var content = document.getElementById("new_content").value;
                            $.ajax
                                    ({
                                        type: 'post',
                                        url: 'comment-add.php',
                                        data: {
                                            insert_row: 'insert_row',
                                            name: name,
                                            website: website,
                                            content: content
                                        },
                                        success: function (response) {
                                            if (response != "")
                                            {
                                                var id = response;
                                                var row = "<div id='name_val" + id + "'>" + name + "</div><div id='website_val" + id + "'>" + website + "</div><div id='content_val" + id + "'>" + content + "</div><input type='button' class='edit_button' id='edit_button" + id + "' value='Edit' onclick='edit_row(" + id + ");'/>";
                                                $('#container').append(row);
                                                document.getElementById("username").value = "";
                                                document.getElementById("website").value = "";
                                                document.getElementById("new_content").value = "";
                                            }

                                            location.reload();
                                        }
                                    });
                            this.close();
                        }
                    }
                ]).show();
    });
});

function edit_row(id)
{
            var name = $.trim(document.getElementById("name_val" + id).innerHTML);
            var website = $.trim(document.getElementById("website_val" + id).innerHTML);
            var content = $.trim(document.getElementById("content_val" + id).innerHTML);
			localStorage.setItem('name',name);
			localStorage.setItem('website',website);
			localStorage.setItem('content',content);
			
		var options = {
		    ajaxPrefix: '',
			 
		};

    new Dialogify('edit-form.php', options)
            .title('Edit Comment')
            .buttons([
                {
                    text: 'Cancel',
                    click: function (e) {
                        console.log('cancel click');
                        this.close();
                    }
                },
                {
                    text: 'Okay',
                    type: Dialogify.BUTTON_PRIMARY,
                    click: function (e) {
					  					   
                        var name = $('#username').val();
                        var website = $('#website').val();
                        var content = $('#edit_content').val();
                        $.ajax
                                ({
                                    type: 'post',
                                    url: 'comment-edit.php',
                                    data: {
                                        edit_row: 'edit_row',
                                        id: id,
                                        name: name,
                                        website: website,
                                        content: content
                                    },
                                    success: function (response) {
                                        if (response == "success")
                                        {
                                            document.getElementById("name_val" + id).innerHTML = name;
                                            document.getElementById("website_val" + id).innerHTML = website;
                                            document.getElementById("content_val" + id).innerHTML = content;
                                        }
                                    }
                                });
                        this.close();

                    }
                }
            ]).show();
			
    $('#username').val(name);
    $('#website').val(website);
    $('#edit_content').val(content);
}

Add Edit Comments Form HTML Loaded to Dialogify Initialization

In this section, the add edit comments from HTML. I have used the Dialogify library initialization method of loading an external source. By specifying the external file source, the HTML content will be loaded to the modal window shown by the Dialogify plugin.

add-form.php

The add-form.php file is written to display the comment add form in a Dialog window. This is the HTML form contains the name, website and comment message fields to get the input from the user. By clicking the Okay button, these fields are loaded to the local object and sent to the server side script to process add action.

<input type="text" class="text-field form-control" id="username"  placeholder="Name"/>
<input type="text" class="text-field form-control" id="website"   placeholder="Website"/>
<textarea type="text" class="text-field form-control" id="new_content"   placeholder="content"></textarea>

edit-form.php

The edit-form.php file also contains the same three fields as it is in the comment-add form. But, the comment data will be prepopulated onto the edit form fields. This pre-population is done programmatically via jQuery. The name, website and the comment content data are got from the local object that is instantiated before.

<input type="text" class="text-field form-control" id="username"
    placeholder="Name" />
<input type="text" class="text-field form-control" id="website"
    placeholder="link" />
<textarea type="text" class="text-field form-control" id="edit_content"
    placeholder="content"></textarea>

<script>
 $(document).ready(function () {
     var name = localStorage.getItem('name');
	 var website = localStorage.getItem('website');
	 var content = localStorage.getItem('content');
    $('#username').val(name);
    $('#website').val(website);
    $('#edit_content').val(content);
 });
 </script>

PHP Code to Add Edit Comments with Database 

In PHP the comments add edit request and parameters are received from the AJAX call. Based on the request type, the query will be created to perform the add or edit action on the comment database. The following code snippets show how the add edit comments action is performed and updated on to the database.

I connect to the database and use the MySQLi prepared statement for the INSERT or UPDATE query to perform the requested action on the comment entity. The posted data and their type are used to build the query param value and param type array respectively.

comment-add.php

<?php
require_once('db.php');

if (isset($_POST['insert_row'])) {
    $sql = $conn->prepare("INSERT INTO tbl_comments (name,website,content) VALUES (?, ?, ?)");
    $name = $_POST['name'];
    $website = $_POST['website'];
    $content = $_POST['content'];
    $sql->bind_param("sss", $name, $website, $content);
    if ($sql->execute()) {
        $success_message = "Added Successfully";
    } else {
        $error_message = "Problem in Adding New Record";
    }
    $sql->close();
    $conn->close();
    exit();
}
?>

comment-edit.php

<?php
require_once('db.php');

if (isset($_POST['edit_row'])) {
    $sql = $conn->prepare("UPDATE tbl_comments SET name=? , website=? , content=?  WHERE id=?");
    $id = $_POST['id'];
    $name = $_POST['name'];
    $website = $_POST['website'];
    $content = $_POST['content'];

    $sql->bind_param("sssi", $name, $website, $content, $id);
    if ($sql->execute()) {
        print "success";
    } else {
        $error_message = "Problem in Editing Record";
    }
}
?>

Database Script

tbl_comments table is used to list add edit comments with this example. Below database script will be required to run this example in your PHP environment.

--
-- Table structure for table `tbl_comments`
--

CREATE TABLE `tbl_comments` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `website` varchar(255) NOT NULL,
  `content` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_comments`
--
ALTER TABLE `tbl_comments`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_comments`
--
ALTER TABLE `tbl_comments`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;

Add Edit Comments using jQuery Dialogify Output

This screenshot shows the Comments add form in a modal window by using Dialogify library. The edit modal will also look like the same but with prepopulated comment data name, website and the content.

Add Edit Comments using jQuery Dialogify Output

Download


↑ Back to Top



Source link
thanks you RSS link
( https://phppot.com/php/add-edit-comments-using-jquery-dialogify/)

LEAVE A REPLY

Please enter your comment!
Please enter your name here