Categories
JavaScript Templating PHP

Minimal Templating with Templater.js

In this application you’ll learn how display data in a table with PHP and MySQL using TemplaterJS it is a tiny JS library for minimal templating.

First we will Create 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 17, 2020 at 08:40 AM
-- 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_vue_product`
--

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

--
-- Table structure for table `products`
--

CREATE TABLE `products` (
  `id` int(11) NOT NULL,
  `namex` varchar(255) NOT NULL,
  `category` varchar(100) NOT NULL,
  `qty` varchar(255) NOT NULL,
  `stock` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `products`
--

INSERT INTO `products` (`id`, `namex`, `category`, `qty`, `stock`) VALUES
(150, '1st Product', 'category 1', '4', 'In Stock'),
(151, '2nd Product', 'category 12', '0', 'Out of stock'),
(186, '3rd Product', 'category 3', '22', 'In Stock'),
(187, '4th Products', 'wwd', '2', 'In Stock');

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `products`
--
ALTER TABLE `products`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=188;
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 “database.php” and put the following code inside it.

<?php
    class Database{ 
        private $db_host = 'localhost';
        private $db_name = 'db_angular_product';
        private $db_username = 'root';
        private $db_password = '';
        
        public function dbConnection(){
            try{
                $conn = new PDO('mysql:host='.$this->db_host.';dbname='.$this->db_name,$this->db_username,$this->db_password);
                $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                return $conn;
            }
            catch(PDOException $e){
                echo "Connection error ".$e->getMessage(); 
                exit;
            } 
        }
    }
?>

Web API Controller

<?php
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Headers: access");
    header("Access-Control-Allow-Methods: POST");
    header("Access-Control-Allow-Credentials: true");
    header("Content-Type: application/json; charset=UTF-8");
    // header("Accept-Encoding", "UTF-8");

    require 'database.php';
    $db_connection = new Database();
    $conn = $db_connection->dbConnection();

    // Raw JSON Parameter
       $data=json_decode(file_get_contents("php://input"));
       
    // Extract the Data Fields
    $action = $data->action;
    switch ($action) 
    {
        case "get_product_list":
            $statement = $conn->prepare("SELECT * FROM products");
            $statement->execute();
            $results=$statement->fetchAll(PDO::FETCH_ASSOC);
            print json_encode($results, JSON_UNESCAPED_UNICODE);
            break;
          }
?>

Creating Simple Page

<!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/css/bootstrap.min.css">
</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>

  <section id="my-app">
    <div class="container">
      <div class="row py-5">
        <div class="table-responsive">
          <table class="table-product table table-bordered table-striped">
            <thead class="thead-product">
              <tr>
                <th style="width:5%">No.</th>
                <th>Name</th>
                <th style="width:15%">Category</th>
                <th style="width:5%">Quantity</th>
                <th style="width:15%">Status</th>
              </tr>
            </thead>
            <tbody id="get_product">

            </tbody>
          </table>
        </div>
      </div>
    </div>
  </section>

  <script src="./assets/jquery/jquery.min.js"></script>
  <script src="./assets/templater/templater.min.js"></script>
  <script src="./assets/js/script.js"></script>

  <script id="product_list_data" type="text/template">
    <tr>
      <td>{{ id }}</td>
      <td>{{ namex }}</td>
      <td>{{ category }}</td>
      <td>{{ qty }}</td>
      <td><span class="badge badge-default">{{ stock }}</span></td>
    </tr>
  </script>

</body>

</html>

Ajax Request function

$(document).ready(function () {
	var tmpl = $("#product_list_data").html();
	$.ajax({
		method: "POST",
		url: "./library/api.php",
		dataType: 'json',
		contentType: 'application/json',
		data: JSON.stringify({ "action": "get_product_list" }),
		success: function (prodData) {
			$.each(prodData, function (i, product) {
				const template = templater(tmpl);
				$('#get_product').append(template(product));
			});
		}
	});
})

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!

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!

Categories
JavaScript Templating PHP

Ajax request with Mustache.js

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

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 data table showing the records from the “tbl_products” database table. We’ll include mustache Autoloader it require mustache to render our templates.

 <?php 
include('src/mustache/Autoloader.php');
Mustache_Autoloader::register();
$entry = new Mustache_Engine;
$product_list_template = file_get_contents('template/product_list.mustache');
?>

 <!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">
     <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>

           <?php echo $entry->render($product_list_template); ?>
         </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/mustache/js/mustache.min.js"></script>
   <script src="./assets/js/render.js"></script>
 </body>

 </html>

This is a shorthand Ajax function

$(document).ready(function () {
  var template = $("#product_list_data").html();
  $(function () {
    $.getJSON('product_list.php',
      function (prodData) {

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

      });
  });
})

which is equal to

$(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 = Mustache.render(template, product);
        $('#get_product').append(html);
      });

    }
  });
})

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 to 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!