This tutorial explains how to insert and load records in mysql table and update the html content without page refreshing using jquery, ajax, php. 

Create messages table in mysql:
=======================

Below is the structure of messages table with basic fields. 

  CREATE TABLE `messages` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `message` TEXT NULL,
  `created_at` DATETIME NULL,
  `updated_at` DATETIME NULL,
  PRIMARY KEY (`id`));


Create Connection(config.php) 
=======================

Connect to the database. In config.php add your database name, database username, database password and database name.

<?php
//Database details
$db_host = 'localhost';
$db_username = 'username';
$db_password = 'password';
$db_name = 'database_name';

//Create connection and select DB
$conn = mysqli_connect($db_host, $db_username, $db_password, $db_name);
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

index.php
=======

<!--
Used basic html and bootstrap skeleton from the below link for style purpose which contains bootstrap.css, bootstrap.js, jquery.js
https://www.w3schools.com/bootstrap/bootstrap_get_started.asp

Used bootstrap form elements from below link.
https://www.w3schools.com/bootstrap/bootstrap_forms.asp
-->
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Insert and load records using Jquery,Ajax and Php without refreshing page</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <style>
            .error{
                color:red;
                font-size:13px;
            }
            .message-wrap{
                background: #e6ecf0;
                color: #000;
                padding: 15px;
                margin-top:10px;
                margin-bottom: 10px;
            }
            .dn{
                display: none;
            }
        </style>
    </head>
    <body>
        <div class="container" style="max-width:800px;margin:0 auto;margin-top:50px;">  
            <div>
                <h2 style="margin-bottom:50px;">Live Demo: Insert and load records using Jquery,Ajax and Php without refreshing page</h2>
                <div class="form-group">
                    <label for="email">What are you doing today?</label>
                    <textarea name="message" class="form-control" id="message"></textarea>
                    <div class="error" id="error_message"></div>
                </div>
                <div class="form-group">
                    <button class="btn btn-success" id="save">Save</button>
                </div>

                <div class="display-content">

                    <div class="message-wrap dn">                      
                    </div>
                </div>
            </div>
        </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <script>
            $(document).on("click", "#save", function () {
                //get value of message 
                var message = $("#message").val();
                //check if value is not empty
                if (message == "") {
                    $("#error_message").html("Please enter message");
                    return false;
                } else {
                    $("#error_message").html("");
                }
                //Ajax call to send data to the insert.php
                $.ajax({
                    type: "POST",
                    url: "insert.php",
                    data: {message: message},
                    cache: false,
                    success: function (data) {
                        //Insert data before the message wrap div
                        $(data).insertBefore(".message-wrap:first");
                        //Clear the textarea message
                        $("#message").val("");
                    }
                });
            });
        </script>
    </body>
</html>


insert.php
========

<?php
require_once 'config.php';
if (isset($_POST['message'])) {
    $message = $_POST['message'];
    mysqli_query($conn, "insert into messages(message) values ('$message')");
    $sql = mysqli_query($conn, "SELECT message,id FROM messages order by id desc");
    $result = mysqli_fetch_array($sql);
    echo '<div class="message-wrap">' . $result['message'] . '</div>';
} else {
    echo "Message is empty";
}
?>

Written by
Check out this Author's contributed articles.
If you like Tutorialsmint and would like to contribute, you can also write an article using Write an Article. See your article appearing on the Tutorialsmint main page and help other programmers to enhance their knowledge.

Comments(0)

RECENT TUTORIALS
Wed Dec 26 • 08:00 AM GMT
Wed Dec 26 • 08:00 AM GMT
Wed Dec 26 • 08:00 AM GMT
Wed Dec 26 • 08:00 AM GMT
Wed Dec 26 • 08:00 AM GMT
Edit Post
Add Reply