Categories
JavaScript Templating PHP

Ajax request with Handlebars.js

In this application you’ll learn how use Handlebars.js to render template and display data in a table with PHP and MySQL.

First get the latest file for handlebars here https://www.npmjs.com/package/handlebars

Creating the Database Table

Execute SQL Dump file

-- phpMyAdmin SQL Dump
-- version 4.8.5
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Apr 12, 2020 at 01:28 PM
-- Server version: 10.1.38-MariaDB
-- PHP Version: 7.1.27

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `db_product`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_products`
--

CREATE TABLE `tbl_products` (
  `id` int(11) NOT NULL,
  `name` varchar(200) NOT NULL,
  `sku` varchar(100) NOT NULL,
  `price` varchar(50) NOT NULL,
  `qty` varchar(50) NOT NULL,
  `description` text NOT NULL,
  `availability` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_products`
--

INSERT INTO `tbl_products` (`id`, `name`, `sku`, `price`, `qty`, `description`, `availability`) VALUES
(4, 'Second Item', 'sku-1234', '2000', '456', 'Loerem ipsum ', '120'),
(48, 'First Item', 'sku-122', '20', '1000', 'lorem ipsumssss', '0'),
(49, 'Third item', 'sku-55', '800', '6', 'Sana All', '20');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_products`
--
ALTER TABLE `tbl_products`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `id` (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_products`
--
ALTER TABLE `tbl_products`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=50;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Creating the Connection File

After creating the table, we need to setup your database connection copy and paste the code below in order to connect to the MySQL database server. Let’s create and name it to “db_conn.php” and put the following code inside it.

<?php 
    $conn=mysqli_connect("localhost", "root", "", "db_product");

        if(!$conn){
            die("Error: Failed To Connect Database!");
        }
?>

Creating Simple Page

First we will create simple page for our application it contains a script template to display records in a table from the “tbl_products” database table. Copy and paste the code below

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Proghubsterzeak</title>
  <link rel="stylesheet" href="./assets/bootstrap/bootstrap.min.css">
  <style>
  footer {
    position: absolute;
    width: 100%;
    bottom: 0;
  }
  </style>
</head>

<body>
  <header>
    <nav class="navbar navbar-light bg-light">
      <span class="navbar-text">
        <a href="https://proghubsterzeak.com/"> https://proghubsterzeak.com</a>
      </span>
    </nav>
  </header>
  <main class="py-5">
    <script id="product_list_data" type="text/template">
      <tr>
        <td>{{id}}</td>
        <td>{{name}}</td>
        <td>{{sku}}</td>
        <td>{{price}}</td>
        <td>{{qty}}</td>
        <td>{{description}}</td>
        <td>{{availability}}</td>
      </tr>
  </script>

    <section>
      <div class="container">
        <table class="table">
          <table id='load-data' class='table table-striped table-bordered' style='width:100%'>
            <thead class="thead-dark">
              <tr>
                <th>#</th>
                <th>Product Name</th>
                <th>SKU</th>
                <th>Amount</th>
                <th>Quantity</th>
                <th>Description</th>
                <th>Availability</th>
              </tr>
            </thead>
            <tbody id="get_product">
            </tbody>
          </table>
        </table>
      </div>
    </section>
  </main>
  <footer class="text-center py-2 bg-light">
    © 2020 Your Site
  </footer>
  <script src="./assets/jquery/jquery.min.js"></script>
  <script src="./assets/handlebars/handlebars.min.js"></script>
  <script src="./assets/js/render.js"></script>
</body>

</html>

ajax request

$(document).ready(function () {
  var template = $("#product_list_data").html();
  $.ajax({
    url: 'product_list.php',
    dataType: "json",
    success: function (prodData) {

      $.each(prodData, function (i, product) {
        var html = Handlebars.compile(template);
        $('#get_product').append(html(product));
      });

    }
  });
})

Copy and paste the code below and save it as product_list.php. This code will simply retrieve the records from the “tbl_products” table from database and it will return as JSON.

<?php
	require_once 'db_con.php';
	$bacth = array();

	$queryretrieve=mysqli_query($conn,"SELECT * FROM tbl_products");
	$n = mysqli_num_rows($queryretrieve);

	if ($n!=0) {
		while($result = mysqli_fetch_array($queryretrieve)){
			$bacth[] = $result;
	} 
	echo json_encode($bacth);
	}
?>

Download the complete source code. For more information about the system. You can contact me @ Email – larrydaveemol@gmail.com

Let me know what you need just leave a message/comment and I will do my very best to make that happen. I hope this codes will help you. Enjoy Coding!