Monday, 27 March 2017

How to use Morris.js chart with PHP & Mysql



This post cover one of the advance topic like how to implement Mysql data with Morris.js Chart to make stylish chart by using PHP Script. In one of the our previous post in which we have seen how to use Google Chart Library with PHP and Mysql database. But now we have seen one more Chart library and how to use this Morris.js chart library with PHP and Mysql.

We have already know most of data in any web based application are comes from the sourced of database and based on that data we want required to display that data in chart or graph format on web page. So display of database data under graph or chart visualization on web page is the headache for most of the programmer and this task required lost of steps to display data in graph or chart format. But after coming of Morris.js charts, it makes this work more easier than previously which we have done for make chart from data. We have only make simple Mysql query and execute query and pass query result to Morris charts javascript and after this it will make chart as per our requirement. Morris.js Charts library is our best loved library for displaying data in charts format on web page.

In this post we will first make simple query and make data for Morris.js chart, based on that data we will make Line chart, Area chart, Bar chart and Bar chart with stacked option. For making this chart we have take data of last 10 years profit, purchase and sale data from Mysql table.




First we have load required cdn library link for use Morris.js chart with PHP and Mysql


<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>


After defining required CDN library link, we have create on division tag and we will display chart under this tag.


<div id="chart"></div>


For fetch data from table we have write php code for fetch data from Mysql table and arrange them that data in format which are allowed in Morris.js charts javascript library.


<?php 
//index.php
$connect = mysqli_connect("localhost", "root", "", "testing");
$query = "SELECT * FROM account";
$result = mysqli_query($connect, $query);
$chart_data = '';
while($row = mysqli_fetch_array($result))
{
 $chart_data .= "{ year:'".$row["year"]."', profit:".$row["profit"].", purchase:".$row["purchase"].", sale:".$row["sale"]."}, ";
}
$chart_data = substr($chart_data, 0, -2);
?>


After fetching data from Mysql table now we have write javscript code for load Morris.js chart library for different chart like Line chart, Area chart, Bar chart and Bar chart with stacked option.


<script>
Morris.Bar({
 element : 'chart',
 data:[<?php echo $chart_data; ?>],
 xkey:'year',
 ykeys:['profit', 'purchase', 'sale'],
 labels:['Profit', 'Purchase', 'Sale'],
 hideHover:'auto',
 stacked:true
});
</script>


This is something new web tutorial make by Webslesson, with this post you can get source code of this tutorial and you can also get video tutorial on this topic also.

Source Code


index.php



<?php 
//index.php
$connect = mysqli_connect("localhost", "root", "", "testing");
$query = "SELECT * FROM account";
$result = mysqli_query($connect, $query);
$chart_data = '';
while($row = mysqli_fetch_array($result))
{
 $chart_data .= "{ year:'".$row["year"]."', profit:".$row["profit"].", purchase:".$row["purchase"].", sale:".$row["sale"]."}, ";
}
$chart_data = substr($chart_data, 0, -2);
?>


<!DOCTYPE html>
<html>
 <head>
  <title>Webslesson Tutorial | How to use Morris.js chart with PHP & Mysql</title>
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
  
 </head>
 <body>
  <br /><br />
  <div class="container" style="width:900px;">
   <h2 align="center">Morris.js chart with PHP & Mysql</h2>
   <h3 align="center">Last 10 Years Profit, Purchase and Sale Data</h3>   
   <br /><br />
   <div id="chart"></div>
  </div>
 </body>
</html>

<script>
Morris.Bar({
 element : 'chart',
 data:[<?php echo $chart_data; ?>],
 xkey:'year',
 ykeys:['profit', 'purchase', 'sale'],
 labels:['Profit', 'Purchase', 'Sale'],
 hideHover:'auto',
 stacked:true
});
</script>


Database



--
-- Database: `testing`
--

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

--
-- Table structure for table `account`
--

CREATE TABLE IF NOT EXISTS `account` (
  `id` int(11) NOT NULL,
  `year` int(11) NOT NULL,
  `purchase` int(11) NOT NULL,
  `sale` int(11) NOT NULL,
  `profit` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `account`
--

INSERT INTO `account` (`id`, `year`, `purchase`, `sale`, `profit`) VALUES
(1, 2007, 550000, 800000, 250000),
(2, 2008, 678000, 1065000, 387000),
(3, 2009, 787000, 1278500, 491500),
(4, 2010, 895600, 1456000, 560400),
(5, 2011, 967150, 1675600, 708450),
(6, 2012, 1065850, 1701542, 635692),
(7, 2013, 1105600, 1895000, 789400),
(8, 2014, 1465000, 2256500, 791500),
(9, 2015, 1674500, 2530000, 855500),
(10, 2016, 2050000, 3160000, 1110000);

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

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

Friday, 24 March 2017

Ajax Jquery Shopping cart by using Codeigniter Cart Library



In this post we have make shopping cart by using Codeigniter Cart library. We have also use how to use Ajax JQuery with Codeigniter Cart class while making shopping cart. So we will shopping cart in which we can add item into cart without refreshing of web page. A Shopping cart is a simple web application that are use to make eCommerce web site on which you can create your online store and you can sale item online and order processing.

Here we have use Codeigniter Cart class with Ajax JQuery to make simple shopping cart. Codeigniter Cart library has been initialize Session cart and it will store all cart data in session. So when user will refresh page or browse on another tag and again going to cart page then he can view his item on web page in cart.

Codeigniter Cart Class provide core cart functionality it is not provide complete solution for online store but by using this class you can make shopping cart in which you can add item into cart, update item of the cart, you can remove item from cart, it also provide particular item sub total also, if you want to get the whole cart total also get by using this cart. If you want to clear whole cart item then by single click you can also remove all items from cart. You can perform all this operation without writing many lines of code but you can perform this all operation in single line of code.




For initialize Codeigniter cart class in your application, you have to write this code.


$this->load->library("cart");


After initialize Codeigniter Cart library, suppose you want to add some item into cart then first you have to make array and in that array you have to define four keys like "id", "name", "qty", "price". This four keys are required field in cart library. Suppose you have miss any key then it will not add item into cart. After this suppose you want to add more field then in fifth keys you can write "options" with value and in value you can define extra field in array format with value. But you want to add only one fields then you have to simply write name in keys and value define in value.


$data = array(
   "id"  => $_POST["product_id"],
   "name"  => $_POST["product_name"],
   "qty"  => $_POST["quantity"],
   "price"  => $_POST["product_price"]
);


For Insert above item details into cart we have use insert() method of this library and it will insert item into cart. When we have you this method for insert item into cart then it will return rowid value. It identify unique id of particular item detail in cart.


$this->cart->insert($data);


After insert item into cart now we want to fetch cart item and display on web page. So we have use this class contents() method which return array of cart item. When we have use this method then we can fetch cart item one by one. Suppose we want to get sub total of single item then this method will return single item sub total get from subtotal array variable. Here we have also define remove button also with class remove_inventory we will use as selector in jquery code and in id attribute we have store rowid variable value. From this variable we will get the unique id of particular item. For get the whole cart total, so we can use total() method of this class which return total of whole cart.


$output = '';
  $output .= '
  <h3>Shopping Cart</h3><br />
  <div class="table-responsive">
   <div align="right">
    <button type="button" id="clear_cart" class="btn btn-warning">Clear Cart</button>
   </div>
   <br />
   <table class="table table-bordered">
    <tr>
     <th width="40%">Name</th>
     <th width="15%">Quantity</th>
     <th width="15%">Price</th>
     <th width="15%">Total</th>
     <th width="15%">Action</th>
    </tr>

  ';
  $count = 0;
  foreach($this->cart->contents() as $items)
  {
   $count++;
   $output .= '
   <tr> 
    <td>'.$items["name"].'</td>
    <td>'.$items["qty"].'</td>
    <td>'.$items["price"].'</td>
    <td>'.$items["subtotal"].'</td>
    <td><button type="button" name="remove" class="btn btn-danger btn-xs remove_inventory" id="'.$items["rowid"].'">Remove</button></td>
   </tr>
   ';
  }
  $output .= '
   <tr>
    <td colspan="4" align="right">Total</td>
    <td>'.$this->cart->total().'</td>
   </tr>
  </table>

  </div>
  ';

  if($count == 0)
  {
   $output = '<h3 align="center">Cart is Empty</h3>';
  }
  return $output;


After viewing cart item on web page now we want to remove single item from shopping cart. So we want to get unique rowid of particular item. After getting this value then after we have make one array with keys like rowid and quantity. In quantity key we have store zero as value. After this we have use update() and we have update particular item quantity to zero. In this cart library when quantity value will be zero then it will automatically remove that item. So this way we can remove single item from Codeigniter Shopping cart library.


               $row_id = $_POST["row_id"];
  $data = array(
   'rowid'  => $row_id,
   'qty'  => 0
  );
  $this->cart->update($data);


Suppose you want to remove all items from the cart, then it is very easy in Codeigniter class. You have to use only simple destroy() method of this library. This method will remove all items from this cart and it will display empty cart.


$this->cart->destroy();


So, this is complete details of how to use Codeigniter Cart Library to make simple shopping cart. In this post you can find video tutorial of this post and source code also. If you have any query regarding this post, please comment your query under comment box.

Source Code


Controllers - Shopping_cart.php



<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Shopping_cart extends CI_Controller {
 
 function index()
 {
  $this->load->model("shopping_cart_model");
  $data["product"] = $this->shopping_cart_model->fetch_all();
  $this->load->view("shopping_cart", $data);
 }

 function add()
 {
  $this->load->library("cart");
  $data = array(
   "id"  => $_POST["product_id"],
   "name"  => $_POST["product_name"],
   "qty"  => $_POST["quantity"],
   "price"  => $_POST["product_price"]
  );
  $this->cart->insert($data); //return rowid 
  echo $this->view();
 }

 function load()
 {
  echo $this->view();
 }

 function remove()
 {
  $this->load->library("cart");
  $row_id = $_POST["row_id"];
  $data = array(
   'rowid'  => $row_id,
   'qty'  => 0
  );
  $this->cart->update($data);
  echo $this->view();
 }

 function clear()
 {
  $this->load->library("cart");
  $this->cart->destroy();
  echo $this->view();
 }
 
 function view()
 {
  $this->load->library("cart");
  $output = '';
  $output .= '
  <h3>Shopping Cart</h3><br />
  <div class="table-responsive">
   <div align="right">
    <button type="button" id="clear_cart" class="btn btn-warning">Clear Cart</button>
   </div>
   <br />
   <table class="table table-bordered">
    <tr>
     <th width="40%">Name</th>
     <th width="15%">Quantity</th>
     <th width="15%">Price</th>
     <th width="15%">Total</th>
     <th width="15%">Action</th>
    </tr>

  ';
  $count = 0;
  foreach($this->cart->contents() as $items)
  {
   $count++;
   $output .= '
   <tr> 
    <td>'.$items["name"].'</td>
    <td>'.$items["qty"].'</td>
    <td>'.$items["price"].'</td>
    <td>'.$items["subtotal"].'</td>
    <td><button type="button" name="remove" class="btn btn-danger btn-xs remove_inventory" id="'.$items["rowid"].'">Remove</button></td>
   </tr>
   ';
  }
  $output .= '
   <tr>
    <td colspan="4" align="right">Total</td>
    <td>'.$this->cart->total().'</td>
   </tr>
  </table>

  </div>
  ';

  if($count == 0)
  {
   $output = '<h3 align="center">Cart is Empty</h3>';
  }
  return $output;
 }
}


Models - Shopping_cart_model.php



<?php
class Shopping_cart_model extends CI_Model
{
 function fetch_all()
 {
  $query = $this->db->get("product");
  return $query->result();
 }
}



Views - shopping_cart.php



<html>
<head>
    <title>Codeigniter Shopping Cart with Ajax JQuery</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
 <br /><br />
 
 <div class="col-lg-6 col-md-6">
  <div class="table-responsive">
   <h3 align="center">Codeigniter Shopping Cart with Ajax JQuery</h3><br />
   <?php
   foreach($product as $row)
   {
    echo '
    <div class="col-md-4" style="padding:16px; background-color:#f1f1f1; border:1px solid #ccc; margin-bottom:16px; height:400px" align="center">
     <img src="'.base_url().'images/'.$row->product_image.'" class="img-thumbnail" /><br />
     <h4>'.$row->product_name.'</h4>
     <h3 class="text-danger">$'.$row->product_price.'</h3>
     <input type="text" name="quantity" class="form-control quantity" id="'.$row->product_id.'" /><br />
     <button type="button" name="add_cart" class="btn btn-success add_cart" data-productname="'.$row->product_name.'" data-price="'.$row->product_price.'" data-productid="'.$row->product_id.'" />Add to Cart</button>
    </div>
    ';
   }
   ?>
      
  </div>
 </div>
 <div class="col-lg-6 col-md-6">
  <div id="cart_details">
   <h3 align="center">Cart is Empty</h3>
  </div>
 </div>
 
</div>
</body>
</html>
<script>
$(document).ready(function(){
 
 $('.add_cart').click(function(){
  var product_id = $(this).data("productid");
  var product_name = $(this).data("productname");
  var product_price = $(this).data("price");
  var quantity = $('#' + product_id).val();
  if(quantity != '' && quantity > 0)
  {
   $.ajax({
    url:"<?php echo base_url(); ?>shopping_cart/add",
    method:"POST",
    data:{product_id:product_id, product_name:product_name, product_price:product_price, quantity:quantity},
    success:function(data)
    {
     alert("Product Added into Cart");
     $('#cart_details').html(data);
     $('#' + product_id).val('');
    }
   });
  }
  else
  {
   alert("Please Enter quantity");
  }
 });

 $('#cart_details').load("<?php echo base_url(); ?>shopping_cart/load");

 $(document).on('click', '.remove_inventory', function(){
  var row_id = $(this).attr("id");
  if(confirm("Are you sure you want to remove this?"))
  {
   $.ajax({
    url:"<?php echo base_url(); ?>shopping_cart/remove",
    method:"POST",
    data:{row_id:row_id},
    success:function(data)
    {
     alert("Product removed from Cart");
     $('#cart_details').html(data);
    }
   });
  }
  else
  {
   return false;
  }
 });

 $(document).on('click', '#clear_cart', function(){
  if(confirm("Are you sure you want to clear cart?"))
  {
   $.ajax({
    url:"<?php echo base_url(); ?>shopping_cart/clear",
    success:function(data)
    {
     alert("Your cart has been clear...");
     $('#cart_details').html(data);
    }
   });
  }
  else
  {
   return false;
  }
 });

});
</script>


Database



--
-- Database: `testing1`
--

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

--
-- Table structure for table `product`
--

CREATE TABLE IF NOT EXISTS `product` (
  `product_id` int(11) NOT NULL,
  `category_id` int(11) NOT NULL,
  `product_name` varchar(250) NOT NULL,
  `product_price` varchar(30) NOT NULL,
  `product_image` varchar(250) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `product`
--

INSERT INTO `product` (`product_id`, `category_id`, `product_name`, `product_price`, `product_image`) VALUES
(1, 1, 'ASUS Laptop 1500', '799.00', 'asus-laptop.jpg'),
(2, 1, 'Microsoft Surface Pro 3', '898.00', 'surface-pro.jpg'),
(3, 1, 'Samsung EVO 32GB', '12.00', 'samsung-sd-card.jpg'),
(4, 1, 'Desktop Hard Drive', '50.00', 'computer-hard-disk.jpg'),
(5, 1, 'External Hard Drive', '80.00', 'external-hard-disk.jpg'),
(6, 2, 'Crock-Pot Oval Slow Cooker', '34.00', 'crok-pot-cooker.jpg'),
(7, 2, 'Magic Blender System', '80.00', 'blender.jpg'),
(8, 2, 'Cordless Hand Vacuum', '40.00', 'vaccum-cleaner.jpg'),
(9, 2, 'Dishwasher Detergent', '15.00', 'detergent-powder.jpg'),
(10, 2, 'Essential Oil Diffuser', '20.00', 'unpower-difuser.jpg'),
(11, 3, 'Medical Personalized', '11.00', 'hand-bag.jpg'),
(12, 3, 'Best Bridle Leather Belt', '64.00', 'mens-belt.jpg'),
(13, 3, 'HANDMADE Bow set', '24.00', 'pastal-colors.jpg'),
(14, 3, 'Ceramic Coffee Mug', '18.00', 'coffee-mug.jpg'),
(15, 3, 'Wine Birthday Glass', '18.00', 'wine-glass.jpg');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `product`
--
ALTER TABLE `product`
  ADD PRIMARY KEY (`product_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `product`
--
ALTER TABLE `product`
  MODIFY `product_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=16;

Thursday, 16 March 2017

Ajax JQuery Pagination in Codeigniter using Bootstrap


Hi, In this post we have describe how to make Pagination in Codeigniter by using Codeigniter Pagination library with Jquery Ajax and Bootstrap. Because Codeigniter has rich pagination library by default. We have try many times to implement Codeigniter Pagination library with Jquery Ajax. But we have not get success. After We have try in Codeigniter 3.0 Framework after long time we have again try and we have get success to implement Codeigniter Pagination library with Ajax JQuery and Bootstrap and make pagination in Codeigniter by using Ajax JQuery with Bootstrap.

First we have make Ajax_pagination.php controller in Controllers folder and then after we have make index function and in that function we have load ajax_pagination.php view file from views folder. In that file we will display Codeigniter pagination.


<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Ajax_pagination extends CI_Controller {
 
 function index()
 {
  $this->load->view("ajax_pagination");
 }


After then in view file we have define two division tag, in on division tag we will display pagination link which are made by Codeigniter pagination library and in second tag we will display mysql table data in html format.


<div align="right" id="pagination_link"></div>
<div class="table-responsive" id="country_table"></div>


Then after we have write Jquery code for fetch data with pagination link from Ajax_pagination.php controllers, so we have make one simple load_country_data(page) function. In this function we have send request to controllers function for fetch particular page data with pagination link by using Ajax request. In Ajax request we have use GET method and json data type. This function will fetch data and pagination links from controllers and display on define division tag on webpage without refreshing of page. We have called this function with page argument value is equal to one. So when page has been load this function will be called and it display data and pagination on web page.


<script>
$(document).ready(function(){

 function load_country_data(page)
 {
  $.ajax({
   url:"<?php echo base_url(); ?>ajax_pagination/pagination/"+page,
   method:"GET",
   dataType:"json",
   success:function(data)
   {
    $('#country_table').html(data.country_table);
    $('#pagination_link').html(data.pagination_link);
   }
  });
 }
 
 load_country_data(1);

});
</script>




After creating JQuery function we have move to write pagination function in Ajax_pagination.php controllers. Under this function we have load Codeigniter pagination library. For initialize pagination library first we have define required configuration for initialize pagination library. In Codeigniter pagination library configuration we have define total rows which we have fetch from model count all() function, how many data should be display per page, We have use Bootstrap framework for pagination so we have define pagination class under full_tag_open configuration. Then after we have define html tag for different open and close tag in pagination configuration. After defining all configuration we have initialize pagination library in this function.

For create pagination link we have use pagination library create_links() method. This method has make pagination link. After making pagination link we want particular page data, so we have get that data from ajax_pagination_model 's fetch_details() function, this function will return particular page data. After making pagination link and page data now we want send this data to ajax request in json format, so we have use json_encode() function which convert php array to json string.


function pagination()
 {
  $this->load->model("ajax_pagination_model");
  $this->load->library("pagination");
  $config = array();
  $config["base_url"] = "#";
  $config["total_rows"] = $this->ajax_pagination_model->count_all();
  $config["per_page"] = 10;
  $config["uri_segment"] = 3;
  $config["use_page_numbers"] = TRUE;
  $config["full_tag_open"] = '<ul class="pagination">';
  $config["full_tag_close"] = '</ul>';
  $config["first_tag_open"] = '<li>';
  $config["first_tag_close"] = '</li>';
  $config["last_tag_open"] = '<li>';
  $config["last_tag_close"] = '</li>';
  $config['next_link'] = '&gt;';
  $config["next_tag_open"] = '<li>';
  $config["next_tag_close"] = '</li>';
  $config["prev_link"] = "&lt;";
  $config["prev_tag_open"] = "<li>";
  $config["prev_tag_close"] = "</li>";
  $config["cur_tag_open"] = "<li class='active'><a href='#'>";
  $config["cur_tag_close"] = "</a></li>";
  $config["num_tag_open"] = "<li>";
  $config["num_tag_close"] = "</li>";
  $config["num_links"] = 1;
  $this->pagination->initialize($config);
  $page = $this->uri->segment(3);
  $start = ($page - 1) * $config["per_page"];

  $output = array(
   'pagination_link'  => $this->pagination->create_links(),
   'country_table'   => $this->ajax_pagination_model->fetch_details($config["per_page"], $start)
  );
  echo json_encode($output);
 }


Now we have make one Ajax_pagination_model.php model in models folder, this will perform role as back end, which fetch data from mysql table and send to controllers. Here we have make two function. First function return the number of rows in table and second function fetch data for particular table and return that data in html table format to controllers.


<?php
class Ajax_pagination_model extends CI_Model
{
 function count_all()
 {
  $query = $this->db->get("countries");
  return $query->num_rows();
 }

 function fetch_details($limit, $start)
 {
  $output = '';
  $this->db->select("*");
  $this->db->from("countries");
  $this->db->order_by("name", "ASC");
  $this->db->limit($limit, $start);
  $query = $this->db->get();
  $output .= '
  <table class="table table-bordered">
   <tr>
    <th>Country ID</th>
    <th>Country Name</th>
   </tr>
  ';
  foreach($query->result() as $row)
  {
   $output .= '
   <tr>
    <td>'.$row->id.'</td>
    <td>'.$row->name.'</td>
   </tr>
   ';
  }
  $output .= '</table>';
  return $output;
 }
}



So when we have load page so it display data and pagination link also but when have click on link it is not working so we have write some jquery code on .pagination li a as selector on click event. So when we have click on pagination link then this code will be execute. When this code execute then it will get page number from data variable like ci-pagination-page on pagination link anchor tag. Based on this data variable we can get page number of particular pagination link. This data variable has been come in Codeigniter 3.0. So After coming this version we can easily implement Ajax JQuery pagination in Codeigniter. So we can get page number and after getting page number we have called load_country_data(page) function, so this function will fetch data of particular page and display on web page.


<script>
$(document).ready(function(){

 $(document).on("click", ".pagination li a", function(event){
  event.preventDefault();
  var page = $(this).data("ci-pagination-page");
  load_country_data(page);
 });

});
</script>


So this way we have make Pagination in Codeigniter by using JQuery Ajax with Bootstrap. We hope you have understand this tutorial. If you have any query regarding this tutorial, please comment your query in comment box.




Source Code


Controllers - Ajax_pagination.php



<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Ajax_pagination extends CI_Controller {
 
 function index()
 {
  $this->load->view("ajax_pagination");
 }

 function pagination()
 {
  $this->load->model("ajax_pagination_model");
  $this->load->library("pagination");
  $config = array();
  $config["base_url"] = "#";
  $config["total_rows"] = $this->ajax_pagination_model->count_all();
  $config["per_page"] = 10;
  $config["uri_segment"] = 3;
  $config["use_page_numbers"] = TRUE;
  $config["full_tag_open"] = '<ul class="pagination">';
  $config["full_tag_close"] = '</ul>';
  $config["first_tag_open"] = '<li>';
  $config["first_tag_close"] = '</li>';
  $config["last_tag_open"] = '<li>';
  $config["last_tag_close"] = '</li>';
  $config['next_link'] = '&gt;';
  $config["next_tag_open"] = '<li>';
  $config["next_tag_close"] = '</li>';
  $config["prev_link"] = "&lt;";
  $config["prev_tag_open"] = "<li>";
  $config["prev_tag_close"] = "</li>";
  $config["cur_tag_open"] = "<li class='active'><a href='#'>";
  $config["cur_tag_close"] = "</a></li>";
  $config["num_tag_open"] = "<li>";
  $config["num_tag_close"] = "</li>";
  $config["num_links"] = 1;
  $this->pagination->initialize($config);
  $page = $this->uri->segment(3);
  $start = ($page - 1) * $config["per_page"];

  $output = array(
   'pagination_link'  => $this->pagination->create_links(),
   'country_table'   => $this->ajax_pagination_model->fetch_details($config["per_page"], $start)
  );
  echo json_encode($output);
 }
 
}


Models - Ajax_pagination_model.php



<?php
class Ajax_pagination_model extends CI_Model
{
 function count_all()
 {
  $query = $this->db->get("countries");
  return $query->num_rows();
 }

 function fetch_details($limit, $start)
 {
  $output = '';
  $this->db->select("*");
  $this->db->from("countries");
  $this->db->order_by("name", "ASC");
  $this->db->limit($limit, $start);
  $query = $this->db->get();
  $output .= '
  <table class="table table-bordered">
   <tr>
    <th>Country ID</th>
    <th>Country Name</th>
   </tr>
  ';
  foreach($query->result() as $row)
  {
   $output .= '
   <tr>
    <td>'.$row->id.'</td>
    <td>'.$row->name.'</td>
   </tr>
   ';
  }
  $output .= '</table>';
  return $output;
 }
}



Views - ajax_pagination.php



<html>
<head>
    <title>Ajax JQuery Pagination in Codeigniter using Bootstrap</title>
    
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    
</head>
<body>
 <div class="container box">
  <h3 align="center">Ajax JQuery Pagination in Codeigniter using Bootstrap</h3>
  <div align="right" id="pagination_link"></div>
  <div class="table-responsive" id="country_table"></div>
 </div>
</body>
</html>
<script>
$(document).ready(function(){

 function load_country_data(page)
 {
  $.ajax({
   url:"<?php echo base_url(); ?>ajax_pagination/pagination/"+page,
   method:"GET",
   dataType:"json",
   success:function(data)
   {
    $('#country_table').html(data.country_table);
    $('#pagination_link').html(data.pagination_link);
   }
  });
 }
 
 load_country_data(1);

 $(document).on("click", ".pagination li a", function(event){
  event.preventDefault();
  var page = $(this).data("ci-pagination-page");
  load_country_data(page);
 });

});
</script>


Tuesday, 14 March 2017

Upload Multiple Files or Images in Codeigniter using Ajax JQuery



We have received many web tutorial request on How can we upload multiple images file without using form in Codeigniter by using Ajax Jquery. So We have this simple web tutorial on multiple file upload in Codeigniter framework by using Ajax with Jquery without refreshing of web page. For making this web tutorial we have use Codeigniter Framework with PHP Ajax and JQuery. By using this code you can upload multiple image file with preview in Codeingiter Framework by using Jquery Ajax and PHP.


class Upload_multiple extends CI_Controller {
 
 function index()
 {
  $this->load->view("upload_multiple");
 }


In this web tutorial we have create multiple_upload.php file in View folder and from controller we have load this file in index() function of Upload_multiple.php file controller. After loading this file from controller then after in that file we have use only simple input file tag with multiple attribute for select multiple file from local source. We have not use any HTML form and we have not submit form data to server. Here when we have select multiple file from our computer then it will be directly uploaded to specified destination. Here we have write jquery code on input file element change event. So when we have select multiple file then it will directly uploaded to server.


<div class="col-md-6" align="right">
  <label>Select Multiple Files</label>
 </div>
 <div class="col-md-6">
  <input type="file" name="files" id="files" multiple />
 </div>
 <div style="clear:both"></div>
 <br />
 <br />
 <div id="uploaded_images"></div>



$('#files').change(function(){
  var files = $('#files')[0].files;
  var error = '';
  var form_data = new FormData();
  for(var count = 0; count<files.length; count++)
  {
   var name = files[count].name;
   var extension = name.split('.').pop().toLowerCase();
   if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
   {
    error += "Invalid " + count + " Image File"
   }
   else
   {
    form_data.append("files[]", files[count]);
   }
  }
  if(error == '')
  {
   $.ajax({
    url:"<?php echo base_url(); ?>upload_multiple/upload", //base_url() return http://localhost/tutorial/codeigniter/
    method:"POST",
    data:form_data,
    contentType:false,
    cache:false,
    processData:false,
    beforeSend:function()
    {
     $('#uploaded_images').html("<label class='text-success'>Uploading...</label>");
    },
    success:function(data)
    {
     $('#uploaded_images').html(data);
     $('#files').val('');
    }
   })
  }
  else
  {
   alert(error);
  }
 });


For sending selecting file to server, first we have create on FormData() object and in that object we have append selected file property into that FormData() object variable in Jquery code. After appending selected file property into form data object variable then after we have use Ajax request and via Ajax request we have send form object variable data to server. This way we have send multiple file property server.


function upload()
 {
  sleep(3);
  if($_FILES["files"]["name"] != '')
  {
   $output = '';
   $config["upload_path"] = './upload/';
   $config["allowed_types"] = 'gif|jpg|png';
   $this->load->library('upload', $config);
   $this->upload->initialize($config);
   for($count = 0; $count<count($_FILES["files"]["name"]); $count++)
   {
    $_FILES["file"]["name"] = $_FILES["files"]["name"][$count];
    $_FILES["file"]["type"] = $_FILES["files"]["type"][$count];
    $_FILES["file"]["tmp_name"] = $_FILES["files"]["tmp_name"][$count];
    $_FILES["file"]["error"] = $_FILES["files"]["error"][$count];
    $_FILES["file"]["size"] = $_FILES["files"]["size"][$count];
    if($this->upload->do_upload('file'))
    {
     $data = $this->upload->data();
     $output .= '
     <div class="col-md-3">
      <img src="'.base_url().'upload/'.$data["file_name"].'" class="img-responsive img-thumbnail" />
     </div>
     ';
    }
   }
   echo $output;   
  }
 }


At server side code we have go to Upload_multiple.php in controller folder, in this first we have define configuration for load upload library. After defining configuration for upload library we have load upload library and then after we have initialize upload library. Then after we have fetch single file property from multiple files and upload one by one to specified destination by using Codeigniter Upload library function do_upload().






Source Code


Controllers - Upload_multiple.php



<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Upload_multiple extends CI_Controller {
 
 function index()
 {
  $this->load->view("upload_multiple");
 }

 function upload()
 {
  sleep(3);
  if($_FILES["files"]["name"] != '')
  {
   $output = '';
   $config["upload_path"] = './upload/';
   $config["allowed_types"] = 'gif|jpg|png';
   $this->load->library('upload', $config);
   $this->upload->initialize($config);
   for($count = 0; $count<count($_FILES["files"]["name"]); $count++)
   {
    $_FILES["file"]["name"] = $_FILES["files"]["name"][$count];
    $_FILES["file"]["type"] = $_FILES["files"]["type"][$count];
    $_FILES["file"]["tmp_name"] = $_FILES["files"]["tmp_name"][$count];
    $_FILES["file"]["error"] = $_FILES["files"]["error"][$count];
    $_FILES["file"]["size"] = $_FILES["files"]["size"][$count];
    if($this->upload->do_upload('file'))
    {
     $data = $this->upload->data();
     $output .= '
     <div class="col-md-3">
      <img src="'.base_url().'upload/'.$data["file_name"].'" class="img-responsive img-thumbnail" />
     </div>
     ';
    }
   }
   echo $output;   
  }
 }
}


Views - upload_multiple.php



<html>
<head>
    <title>Upload Multiple Files in Codeigniter using Ajax JQuery</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
 <br /><br /><br />
 <h3 align="center">Upload Multiple Files in Codeigniter using Ajax JQuery</h3><br />
 
 <div class="col-md-6" align="right">
  <label>Select Multiple Files</label>
 </div>
 <div class="col-md-6">
  <input type="file" name="files" id="files" multiple />
 </div>
 <div style="clear:both"></div>
 <br />
 <br />
 <div id="uploaded_images"></div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
 $('#files').change(function(){
  var files = $('#files')[0].files;
  var error = '';
  var form_data = new FormData();
  for(var count = 0; count<files.length; count++)
  {
   var name = files[count].name;
   var extension = name.split('.').pop().toLowerCase();
   if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
   {
    error += "Invalid " + count + " Image File"
   }
   else
   {
    form_data.append("files[]", files[count]);
   }
  }
  if(error == '')
  {
   $.ajax({
    url:"<?php echo base_url(); ?>upload_multiple/upload", //base_url() return http://localhost/tutorial/codeigniter/
    method:"POST",
    data:form_data,
    contentType:false,
    cache:false,
    processData:false,
    beforeSend:function()
    {
     $('#uploaded_images').html("<label class='text-success'>Uploading...</label>");
    },
    success:function(data)
    {
     $('#uploaded_images').html(data);
     $('#files').val('');
    }
   })
  }
  else
  {
   alert(error);
  }
 });
});
</script>

Saturday, 11 March 2017

Multiple Inline Insert into Mysql using Ajax JQuery in PHP



In this post, we have learn how can we insert multiple HTML5 contenteditable table data to mysql database table using PHP with jQuery and AJAX. For this things we have use HTML5 contenteditable attribute in table, this attribute allows to edit table cells by writing contenteditable attribute as true. So by using this attribute we can enter data to the table cells. Then after we have use Jquery code for append new table cells with contenteditable attribute tag as true. So we can append number of editable table cells and we can enter data into that table cells. Then after we have pass table cell data to PHP Script by using Jquery and Ajax. In Server Side PHP script will clean table cells data and make multiple Insert data query and by using mysqli_multi_query() function we have execute multiple insert query for Insert Multiple data into Mysql table.

For making Multiple Inline Insert data example, we have use HTML5 Contenteditable attribute in table cell for add multiple Item information. By using jQuery code we can append number of blank table row into Item Add table. So at once We can enter multiple item data in the editable table cell and then after we can store those multiple data into mysql database on single clicking of a button. So by using this feature we can enter multiple inline table data insert into mysql table in a single click. For sending data from table to PHP script we have use JQuery for fetching data from table cell and by using Ajax we have send that data to php script and in PHP script make multiple insert query and execute query. So in single click of button we can Insert Multiple Inline data into table without refresh of web page.








Source Code


index.php



<!DOCTYPE html>
<html>
 <head>
  <title>Webslesson Tutorial | Multiple Inline Insert into Mysql using Ajax JQuery in PHP</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  
 </head>
 <body>
  <br /><br />
  <div class="container">
   <br />
   <h2 align="center">Multiple Inline Insert into Mysql using Ajax JQuery in PHP</h2>
   <br />
   <div class="table-responsive">
    <table class="table table-bordered" id="crud_table">
     <tr>
      <th width="30%">Item Name</th>
      <th width="10%">Item Code</th>
      <th width="45%">Description</th>
      <th width="10%">Price</th>
      <th width="5%"></th>
     </tr>
     <tr>
      <td contenteditable="true" class="item_name"></td>
      <td contenteditable="true" class="item_code"></td>
      <td contenteditable="true" class="item_desc"></td>
      <td contenteditable="true" class="item_price"></td>
      <td></td>
     </tr>
    </table>
    <div align="right">
     <button type="button" name="add" id="add" class="btn btn-success btn-xs">+</button>
    </div>
    <div align="center">
     <button type="button" name="save" id="save" class="btn btn-info">Save</button>
    </div>
    <br />
    <div id="inserted_item_data"></div>
   </div>
   
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 var count = 1;
 $('#add').click(function(){
  count = count + 1;
  var html_code = "<tr id='row"+count+"'>";
   html_code += "<td contenteditable='true' class='item_name'></td>";
   html_code += "<td contenteditable='true' class='item_code'></td>";
   html_code += "<td contenteditable='true' class='item_desc'></td>";
   html_code += "<td contenteditable='true' class='item_price' ></td>";
   html_code += "<td><button type='button' name='remove' data-row='row"+count+"' class='btn btn-danger btn-xs remove'>-</button></td>";   
   html_code += "</tr>";  
   $('#crud_table').append(html_code);
 });
 
 $(document).on('click', '.remove', function(){
  var delete_row = $(this).data("row");
  $('#' + delete_row).remove();
 });
 
 $('#save').click(function(){
  var item_name = [];
  var item_code = [];
  var item_desc = [];
  var item_price = [];
  $('.item_name').each(function(){
   item_name.push($(this).text());
  });
  $('.item_code').each(function(){
   item_code.push($(this).text());
  });
  $('.item_desc').each(function(){
   item_desc.push($(this).text());
  });
  $('.item_price').each(function(){
   item_price.push($(this).text());
  });
  $.ajax({
   url:"insert.php",
   method:"POST",
   data:{item_name:item_name, item_code:item_code, item_desc:item_desc, item_price:item_price},
   success:function(data){
    alert(data);
    $("td[contentEditable='true']").text("");
    for(var i=2; i<= count; i++)
    {
     $('tr#'+i+'').remove();
    }
    fetch_item_data();
   }
  });
 });
 
 function fetch_item_data()
 {
  $.ajax({
   url:"fetch.php",
   method:"POST",
   success:function(data)
   {
    $('#inserted_item_data').html(data);
   }
  })
 }
 fetch_item_data();
 
});
</script>


insert.php



<?php
//insert.php
$connect = mysqli_connect("localhost", "root", "", "testing");
if(isset($_POST["item_name"]))
{
 $item_name = $_POST["item_name"];
 $item_code = $_POST["item_code"];
 $item_desc = $_POST["item_desc"];
 $item_price = $_POST["item_price"];
 $query = '';
 for($count = 0; $count<count($item_name); $count++)
 {
  $item_name_clean = mysqli_real_escape_string($connect, $item_name[$count]);
  $item_code_clean = mysqli_real_escape_string($connect, $item_code[$count]);
  $item_desc_clean = mysqli_real_escape_string($connect, $item_desc[$count]);
  $item_price_clean = mysqli_real_escape_string($connect, $item_price[$count]);
  if($item_name_clean != '' && $item_code_clean != '' && $item_desc_clean != '' && $item_price_clean != '')
  {
   $query .= '
   INSERT INTO item(item_name, item_code, item_description, item_price) 
   VALUES("'.$item_name_clean.'", "'.$item_code_clean.'", "'.$item_desc_clean.'", "'.$item_price_clean.'"); 
   ';
  }
 }
 if($query != '')
 {
  if(mysqli_multi_query($connect, $query))
  {
   echo 'Item Data Inserted';
  }
  else
  {
   echo 'Error';
  }
 }
 else
 {
  echo 'All Fields are Required';
 }
}
?>


fetch.php



<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "testing");
$output = '';
$query = "SELECT * FROM item ORDER BY item_id DESC";
$result = mysqli_query($connect, $query);
$output = '
<br />
<h3 align="center">Item Data</h3>
<table class="table table-bordered table-striped">
 <tr>
  <th width="30%">Item Name</th>
  <th width="10%">Item Code</th>
  <th width="50%">Description</th>
  <th width="10%">Price</th>
 </tr>
';
while($row = mysqli_fetch_array($result))
{
 $output .= '
 <tr>
  <td>'.$row["item_name"].'</td>
  <td>'.$row["item_code"].'</td>
  <td>'.$row["item_description"].'</td>
  <td>'.$row["item_price"].'</td>
 </tr>
 ';
}
$output .= '</table>';
echo $output;
?>


Database



--
-- Table structure for table `item`
--

CREATE TABLE IF NOT EXISTS `item` (
  `item_id` int(11) NOT NULL,
  `item_name` varchar(250) NOT NULL,
  `item_code` varchar(250) NOT NULL,
  `item_description` text NOT NULL,
  `item_price` varchar(30) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `item`
--

INSERT INTO `item` (`item_id`, `item_name`, `item_code`, `item_description`, `item_price`) VALUES
(1, 'Grease', 'HP38AST', 'General purpose Grease', '50'),
(2, 'Adhesive Epoxy', 'AS38DM33', 'Sealing epoxy', '20'),
(3, 'Connector 2 Way', 'PH848383', 'To be used for power supply connection in ABB Molding Machine', '500'),
(4, 'Laser Sensor', 'D383', 'Laser sensor for cutting machine', '10'),
(5, 'Power Supply 24V', 'D098', '24 Volt power supply for meter unit packing dept', '5'),
(6, 'V Belt 4', 'S34', 'V Belt for motor coupling drive used in milling machine, cutting machine, vibrator, seprator', '30'),
(7, 'Pressure Sensor', 'P38AST-3938B', 'Pressure sensor 4-20mA unit for storage tanks', '6'),
(8, 'LED Light Bulb', 'L24V3', '\n  LED ights', '100'),
(9, 'Item 1', 'Code1', 'Description1', '10'),
(10, 'Item 2', 'Code 2', 'Description 2', '20'),
(11, 'Item 3 ', 'Code 3 ', 'Description 3 ', '30');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `item`
--
ALTER TABLE `item`
  ADD PRIMARY KEY (`item_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `item`
--
ALTER TABLE `item`
  MODIFY `item_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=12;

Thursday, 9 March 2017

Create Dynamic Tabs by using Bootstrap in PHP Mysql



In this post we have make simple dynamic tab in PHP Script with Mysql Database by using Bootstrap. In previous tutorial by using Bootstrap we have make dynamic menu in php with Ajax load content and We have make Facebook style header notification by using PHP Ajax Jquery with Bootstrap.

This is one more post on Bootstrap and in this post we have implement Bootstrap for create Dynamic Tab in PHP Mysql. By using this feature you can display dynamic data on different tab on same page. Data are present on web page but it invisible and they will be only visible after clicking on that id tab. So We can display many data on same page without going to other page.

For learn this things we have use ecommerce site concept. On Ecommerce site product has been divided on different category and display product based on particular category. So here we have use two table Category and Product. From category table we will make dynamic tab and content of dynamic tab has been fetch from product table. So here also we will display product based on category. Dynamic tab has been created by using Bootstrap framework. So in this tutorial we have Dynamic Bootstrap tabs using PHP Mysql.








Source Code


index.php



<?php
$connect = mysqli_connect("localhost", "root", "", "testing1");
$tab_query = "SELECT * FROM category ORDER BY category_id ASC";
$tab_result = mysqli_query($connect, $tab_query);
$tab_menu = '';
$tab_content = '';
$i = 0;
while($row = mysqli_fetch_array($tab_result))
{
 if($i == 0)
 {
  $tab_menu .= '
   <li class="active"><a href="#'.$row["category_id"].'" data-toggle="tab">'.$row["category_name"].'</a></li>
  ';
  $tab_content .= '
   <div id="'.$row["category_id"].'" class="tab-pane fade in active">
  ';
 }
 else
 {
  $tab_menu .= '
   <li><a href="#'.$row["category_id"].'" data-toggle="tab">'.$row["category_name"].'</a></li>
  ';
  $tab_content .= '
   <div id="'.$row["category_id"].'" class="tab-pane fade">
  ';
 }
 $product_query = "SELECT * FROM product WHERE category_id = '".$row["category_id"]."'";
 $product_result = mysqli_query($connect, $product_query);
 while($sub_row = mysqli_fetch_array($product_result))
 {
  $tab_content .= '
  <div class="col-md-3" style="margin-bottom:36px;">
   <img src="images/'.$sub_row["product_image"].'" class="img-responsive img-thumbnail" />
   <h4>'.$sub_row["product_name"].'</h4>
  </div>
  ';
 }
 $tab_content .= '<div style="clear:both"></div></div>';
 $i++;
}
?>

<!DOCTYPE html>
<html>
 <head>
  <title>Webslesson Tutorial | Create Dynamic Tab by using Bootstrap in PHP Mysql</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">
   <h2 align="center">Create Dynamic Tab by using Bootstrap in PHP Mysql</a></h2>
   <br />
   <ul class="nav nav-tabs">
   <?php
   echo $tab_menu;
   ?>
   </ul>
   <div class="tab-content">
   <br />
   <?php
   echo $tab_content;
   ?>
   </div>
  </div>
 </body>
</html>


Tuesday, 7 March 2017

Dynamic Menu with Dynamic content in PHP using Jquery Ajax



In this post you can find out how to make dynamic menu in PHP and How to load dynamic content into this menu by using Ajax JQuery with PHP. Initializing of web page with dynamic content get from database is a very simple task if you have use Jquery with Ajax. We have already seen many web tutorial on fetch dynamic data fetch from database by using Ajax Jquery on different event.

In this tutorial first we will make dynamic menu from mysql table by using simple PHP Script. For making Dynamic menu we have use Bootstrap Framework navigation bar code. By using Bootstrap Navigation Bar we will make simple menu at header of the page. And after this we will modify code and put PHP script for making dynamic menu. While making of menu we will add one id tag in html list tag and in this tag value we will store dynamic page id which are fetch from table. We will use value of this id in Jquery code for fetching particular page details from Database by using Ajax.

In Jquery code we have make one function. That function will fetch particular page details from database based on page id. When ever this function will called it will fetch page details from database and display on web page. After making of function, we have write jquery code on .nav class of Bootstrap Navigation Bar with list tag. So when ever we have click on menu it will fetch id from list tag. In id we have store the value of page id. After getting value of page id we have called function which fetch particular page data from database. But now this function will received dynamic page id when we have click on any menu item. So this way on every click on menu it load particular page details on web page. So this is our simple web tutorial on Make Dynamic menu in PHP and Load Dynamic content by using Ajax JQuery.






Source Code


index.php

 
  <?php
$connect = mysqli_connect("localhost", "root", "", "testing");
$query = "SELECT * FROM pages";
$result = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
 <head>
  <title>Webslesson Tutorial | Dynamic Menu with Dynamic content in PHP using Jquery Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br /><br />
  <div class="container">
   <br />
   <h2 align="center">Dynamic Menu with Dynamic content in PHP using Jquery Ajax</h2>
   <br />
   <nav class="navbar navbar-inverse">
    <div class="container-fluid">
        <div class="navbar-header">
           <a class="navbar-brand" href="#">Webslesson Tutorial</a>
        </div>
        <ul class="nav navbar-nav">
      <?php
      while($row = mysqli_fetch_array($result))
      {
       echo '
       <li id="'.$row["page_id"].'"><a href="#">'.$row["page_title"].'</a></li>
       ';
      }
      ?>
        </ul>
     </div>
   </nav>
   <br />
   <span id="page_details"></span>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 
 function load_page_details(id)
 {
  $.ajax({
   url:"fetch.php",
   method:"POST",
   data:{id:id},
   success:function(data)
   {
    $('#page_details').html(data);
   }
  });
 }

 load_page_details(1);

 $('.nav li').click(function(){
  var page_id = $(this).attr("id");
  load_page_details(page_id);
 });
 
 
});
</script>
 

fetch.php


 
  <?php 
//fetch.php
if(isset($_POST["id"]))
{
 $connect = mysqli_connect("localhost", "root", "", "testing");
 $query = "SELECT * FROM pages WHERE page_id = '".$_POST["id"]."'";
 $result = mysqli_query($connect, $query);
 $output = '';
 while($row = mysqli_fetch_array($result))
 {
  $output .= '
  <h1>'.$row["page_title"].'</h1>
  <p>'.$row["page_description"].'</p>
  ';
 }
 echo $output;
}


?>