Wednesday 26 April 2017

How to Load Data in Modal with Next & Previous button by Ajax PHP



If you are looking for tutorial on Bootstrap Modal with Dynamic data, then you in this post you can find not only how to load dynamic data into pop up bootstrap modal but also you can also find previous and next records button also by using Ajax Jquery with PHP. In one of the our previous post we have already made discussion on How to load dynamic data into Bootstrap modal by using Ajax PHP. But in this post we have include feature of previous and next button also.

If you have already load data into Bootstrap modal, so at that time you have seen one id records then after if you want to see next records then you have to close modal and click on next records view button. But now we have make simple tutorial in which you can see all records details on single modal by clicking on previous and next button. So on single modal we can see all records details one by one on single click and we do have to go next modal.

So if you have developed any web based application and in that application you have used Bootstrap modal for display dynamic data then you can add this features also. So user can view all records details one by one on single modal by clicking on Previous records button or Next records button. Here if you have load first records button then at that time previous button will be disabled because if you have load first records then there is no previous records so previous button will be disabled at that time and same way if you have view last records then at that time next button will be disabled. So if you have developed any web based application by using PHP Ajax with Bootstrap and if you have load dynamics data into modal then you can add this type of feature also to view previous and next records details on same modal by click on button.

I hope you have learn something new from this post. Please keep visit our website. Here you can also find source code and online demo. So keep enjoying PHP programming.







Source Code


index.php



<?php 
//index.php
$connect = mysqli_connect("localhost", "root", "", "testing");
$query = "SELECT * FROM tbl_posts ORDER BY post_id ASC";
$result = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
 <head>
  <title>Webslesson Tutorial | Modal with Dynamic Previous & Next Data Button by Ajax 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">
   <h2 align="center">Modal with Dynamic Previous & Next Data Button by Ajax PHP</h2>
   <br />
   <div class="table-responsive">
    <table class="table table-striped table-bordered">
     <tr>
      <th>Post</th>
      <th>Post Title</th>
      <th>Author</th>
      <th>View</th>
     </tr>
     <?php
     while($row = mysqli_fetch_array($result))
     {
      echo '
      <tr>
       <td>'.$row["post_id"].'</td>
       <td>'.$row["post_title"].'</td>
       <td>'.$row["post_author"].'</td>
       <td><button type="button" name="view" class="btn btn-info view" id="'.$row["post_id"].'" >View</button></td>
      </tr>
      ';
     }
     ?>
    </table>
   </div>
   
  </div>
 </body>
</html>

<div id="post_modal" class="modal fade">
 <div class="modal-dialog">
  <div class="modal-content"> 
   <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal">&times;</button>
    <h4 class="modal-title">Post Details</h4>
   </div>
   <div class="modal-body" id="post_detail">

   </div>
   <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
   </div>
  </div>
 </div>
</div>


<script>
$(document).ready(function(){
 
 function fetch_post_data(post_id)
 {
  $.ajax({
   url:"fetch.php",
   method:"POST",
   data:{post_id:post_id},
   success:function(data)
   {
    $('#post_modal').modal('show');
    $('#post_detail').html(data);
   }
  });
 }

 $(document).on('click', '.view', function(){
  var post_id = $(this).attr("id");
  fetch_post_data(post_id);
 });

 $(document).on('click', '.previous', function(){
  var post_id = $(this).attr("id");
  fetch_post_data(post_id);
 });

 $(document).on('click', '.next', function(){
  var post_id = $(this).attr("id");
  fetch_post_data(post_id);
 });
 
});
</script>


fetch.php



<?php
//fetch.php
if(isset($_POST["post_id"]))
{
 $connect = mysqli_connect("localhost", "root", "", "testing");
 $output = '';
 $query = "SELECT * FROM tbl_posts WHERE post_id = '".$_POST["post_id"]."'";
 $result = mysqli_query($connect, $query);
 while($row = mysqli_fetch_array($result))
 {
  $output .= '
  <h2>'.$row["post_title"].'</h2>
  <p><label>Author By - '.$row["post_author"].'</label></p>
  <p>'.$row["post_description"].'</p>
  ';
  $query_1 = "SELECT post_id FROM tbl_posts WHERE post_id < '".$_POST['post_id']."' ORDER BY post_id DESC LIMIT 1";
  $result_1 = mysqli_query($connect, $query_1);
  $data_1 = mysqli_fetch_assoc($result_1);
  $query_2 = "SELECT post_id FROM tbl_posts WHERE post_id > '".$_POST['post_id']."' ORDER BY post_id ASC LIMIT 1";
  $result_2 = mysqli_query($connect, $query_2);
  $data_2 = mysqli_fetch_assoc($result_2);
  $if_previous_disable = '';
  $if_next_disable = '';
  if($data_1["post_id"] == "")
  {
   $if_previous_disable = 'disabled';
  }
  if($data_2["post_id"] == "")
  {
   $if_next_disable = 'disabled';
  }
  $output .= '
  <br /><br />
  <div align="center">
   <button type="button" name="previous" class="btn btn-warning btn-sm previous" id="'.$data_1["post_id"].'" '.$if_previous_disable.'>Previous</button>
   <button type="button" name="next" class="btn btn-warning btn-sm next" id="'.$data_2["post_id"].'" '.$if_next_disable.'>Next</button>
  </div>
  <br /><br />
  ';
 }
 echo $output;
}

?>

Monday 24 April 2017

Multiple Select option by using Bootstrap Select Plugin in PHP Ajax



In this post we have learn one more Jquery plugin for Bootstrap framework, here we are going to discuss Bootstrap Select plugin which is useful to make stylish select box with option of multiple selection. This plugin is easily integrate with Bootstrap library. There are many plugin like datepicker, colorpicker, select with search and many more available for Bootstrap, this all plugin we can easily integrate within Bootstrap framework.

Bootstrap Select plugin make stylish Select box with selection of multiple option at one time. By using this plugin you can also activate search feature under selection box also. So if your selection box has many option then at that time this search option will be useful to find option from select box.

In this post we have make discussion on how to use this Bootstrap Select plugin within form select tag and how to activate this plugin on select tag. For initialize this plugin we have to define .selectpicker class into select tag class attribute and then after in JQuery code we have write selectpickert() method with selector of .selectpicker class. By this method we can activate this plugin feature into particular select with class name .selectpickert.

After initialize Bootstrap Select Plugin now we want to submit value of selected multiple option to server, when we have directly submit value of this multiple select box then it will submit value of last selected option, so for submit value of all selected option we have to store value of select box into one hidden field and via value of this hidden field we can submit the value of multiple select box. So this way we can use Bootstrap Select Plugin for web development and we have also discuss how to submit the value of multiple option select box. So if you have develop application and you have want to assign multiple option with search feature then you can use this plugin which is very easy to use and you can also use this plugin with single selection option. So it depends on you how to use this plugin as per requirement.







Source Code


index.php


<!DOCTYPE html>
<html>
 <head>
  <title>Webslesson Tutorial | How to Use Bootstrap Select Plugin with PHP JQuery</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>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.min.js"></script>
  
 </head>
 <body>
  <br /><br />
  <div class="container">
   <br />
   <h2 align="center">How to Use Bootstrap Select Plugin with PHP JQuery</h2>
   <br />
   <div class="col-md-4" style="margin-left:200px;">
    <form method="post" id="multiple_select_form">
     <select name="framework" id="framework" class="form-control selectpicker" data-live-search="true" multiple>
      <option value="Laravel">Laravel</option>
      <option value="Symfony">Symfony</option>
      <option value="Codeigniter">Codeigniter</option>
      <option value="CakePHP">CakePHP</option>
      <option value="Zend">Zend</option>
      <option value="Yii">Yii</option>
      <option value="Slim">Slim</option>
     </select>
     <br /><br />
     <input type="hidden" name="hidden_framework" id="hidden_framework" />
     <input type="submit" name="submit" class="btn btn-info" value="Submit" />
    </form>
    <br />
    
   </div>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 $('.selectpicker').selectpicker();

 $('#framework').change(function(){
  $('#hidden_framework').val($('#framework').val());
 });

 $('#multiple_select_form').on('submit', function(event){
  event.preventDefault();
  if($('#framework').val() != '')
  {
   var form_data = $(this).serialize();
   $.ajax({
    url:"insert.php",
    method:"POST",
    data:form_data,
    success:function(data)
    {
     //console.log(data);
     $('#hidden_framework').val('');
     $('.selectpicker').selectpicker('val', '');
     alert(data);
    }
   })
  }
  else
  {
   alert("Please select framework");
   return false;
  }
 });
});
</script>


insert.php



<?php
//insert.php
/*echo $_POST["framework"];
echo '<br />';
echo $_POST["hidden_framework"];*/

$connect = mysqli_connect("localhost", "root", "", "testing");
$query = "INSERT INTO like_table(framework) VALUES ('".$_POST["hidden_framework"]."')";
if(mysqli_query($connect, $query))
{
 echo 'Data Inserted';
}
?>

Friday 21 April 2017

CSV File to HTML Table Using AJAX jQuery



This is the simple web tutorial in which We are going to learn how to import CSV file into HTML table by using Jquery Ajax method. In simple words we will parse CSV file data and display into HTML table format on web page by using Ajax JQuery method. Here We will not use any JQuery plugin or library for read CSV file and display CSV file data in HTML table. We all know CSV stands for Comma Separated Values file format and in this we have store data in string format which are separated by comma. This format file we can also open excel also so it is widely used for exchange data between application.

Here We have one file which we have stored in our working folder and we want to read data from that CSV file by using Ajax and after getting data in string format we will convert into HTML table by using Jquery. If you have developed any web application and you want to load data from CSV file then you can follow this code in which we do not have used any server side script but we have used simply client side script like Ajax and JQuery. This will not increase load on your system. In this script we will not upload CSV file on our system but we will only give CSV file into Ajax request. So Via Ajax request we can get data from CSV file and by using JavaScript we will converted into HTML table code.

Here we have perform all operation at client side, so no load has been come on our server. By using this script we can load large number of data from CSV file to HTML table. This type of feature is very useful if you have build some large project in which if you want to reduce load on database server, then you have so load some data from CSV file, so it will reduce some on database server. So, this our simple tutorial in which we have display CSV file in HTML Table on web page.








Source Code


index.html



<!DOCTYPE html>
<html>
 <head>
  <title>CSV File to HTML Table Using AJAX jQuery</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">
   <div class="table-responsive">
    <h1 align="center">CSV File to HTML Table Using AJAX jQuery</h1>
    <br />
    <div align="center">
     <button type="button" name="load_data" id="load_data" class="btn btn-info">Load Data</button>
    </div>
    <br />
    <div id="employee_table">
    </div>
   </div>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 $('#load_data').click(function(){
  $.ajax({
   url:"employee.csv",
   dataType:"text",
   success:function(data)
   {
    var employee_data = data.split(/\r?\n|\r/);
    var table_data = '<table class="table table-bordered table-striped">';
    for(var count = 0; count<employee_data.length; count++)
    {
     var cell_data = employee_data[count].split(",");
     table_data += '<tr>';
     for(var cell_count=0; cell_count<cell_data.length; cell_count++)
     {
      if(count === 0)
      {
       table_data += '<th>'+cell_data[cell_count]+'</th>';
      }
      else
      {
       table_data += '<td>'+cell_data[cell_count]+'</td>';
      }
     }
     table_data += '</tr>';
    }
    table_data += '</table>';
    $('#employee_table').html(table_data);
   }
  });
 });
 
});
</script>


employee.csv



Name,Address,Gender,Designation,Age
John Smith,656 Edsel Road Sherman Oaks CA 91403,Male,Manager,40
Clara Berry,63 Woodridge Lane Memphis TN 38138,Male,Programmer,22
Barbra K. Hurley,1241 Canis Heights Drive Los Angeles CA 90017,Female,Service technician,26
Antonio J. Forbes,403 Snyder Avenue Charlotte NC 28208,Male,Falling,32
Charles D. Horst,1636 Walnut Hill Drive Cincinnati OH 45202,Male,Financial investigator,29
Beau L. Clayton,3588 Karen Lane Louisville KY 40223,Male,Extractive metallurgical engin,33
Ramona W. Burns,2170 Ocala Street Orlando FL 32801,Female,Electronic typesetting machine operator,27
Jennifer A. Morrison,2135 Lakeland Terrace Plymouth MI 48170,Female,Rigging chaser,29
Susan Juarez,3177 Horseshoe Lane Norristown PA 19403,Male,Control and valve installe,52
Ellan D. Downie,384 Flynn Street Strongsville OH 44136,Female,Education and training manager,26
Larry T. Williamson,1424 Andell Road Brentwood TN 37027,Male,Teaching assistant,30
Lauren M. Reynolds,4798 Echo Lane Kentwood MI 49512,Female,Internet developer,22
Joseph L. Judge,3717 Junkins Avenue Moultrie GA 31768,Male,Refrigeration mechanic,35
Eric C. Lavelle,1120 Whitetail Lane Dallas TX 75207,Male,Model,21
Cheryl T. Smithers,1203 Abia Martin Drive Commack NY 11725,Female,Personal banker,23
Tonia Diaz,4724 Rocky Road Philadelphia PA 19107,Female,Facilitator,29
Stephanie P. Lederman,2117 Larry Street Waukesha WI 53186,Female,Mental health aide,27
Edward F. Sanchez,2313 Elliott Street Manchester NH 03101,Male,Marine oilerp,28
Peter Parker,403 Snyder Avenue Charlotte NC 28208,Male,Programmer,28
John Smith,384 Flynn Street Strongsville OH 44136,Male,Web Developer,25
Mark Boucher,256 Olive Street NY,Male,Techbical Assistance,23

Thursday 20 April 2017

Dynamic Autocomplete search using Bootstrap Typeahead with PHP Ajax



In this post we have learn how to make Dynamic Autocomplete textbox by using Typeahead Jquery plugin with PHP Ajax. Autocomplete search means which query we have type in textbox then below textbox we have get the search related to that query. So we can easily get which we want to write under textbox by clicking on search result below textbox. In many website we have seen this feature. So in this post we are going to learn this topic like create autocomplete textbox by using Typeahead Jquery Plugin with Ajax PHP.

Typeahead JQuery Plugin is a very popular plugin for create autocomplete feature on input fields in modern web form. The principal objective of using this typeahead plugin is to increase the user understanding by providing idea or a list of potential option based on the text which we have typed while filled a form or search on Google, then we have get instant search. It will saves our time and decreases the number of possible errors, because we have do less possibility a spelling mistake while type under textbox.

Twitter typeaheads is a rapid and advance autocomplete library Which get idea from twitter.com's autocomplete search feature. With this library we can make autocomplete search functionality by putting data in local array or we can also make autocomplete search functionality by using server side database operation also by using Ajax. In this tutorial we will use Mysql database and from this we will fetch data via ajax request by using this Typeahead method.






Source Code



<!DOCTYPE html>
<html>
 <head>
  <title>Webslesson Tutorial | Autocomplete Textbox using Bootstrap Typehead with Ajax PHP</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>  
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
 </head>
 <body>
  <br /><br />
  <div class="container" style="width:600px;">
   <h2 align="center">Autocomplete Textbox using Bootstrap Typeahead with Ajax PHP</h2>
   <br /><br />
   <label>Search Country</label>
   <input type="text" name="country" id="country" class="form-control input-lg" autocomplete="off" placeholder="Type Country Name" />
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 
 $('#country').typeahead({
  source: function(query, result)
  {
   $.ajax({
    url:"fetch.php",
    method:"POST",
    data:{query:query},
    dataType:"json",
    success:function(data)
    {
     result($.map(data, function(item){
      return item;
     }));
    }
   })
  }
 });
 
});
</script>



<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "testing");
$request = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
 SELECT * FROM countries WHERE name LIKE '%".$request."%'
";

$result = mysqli_query($connect, $query);

$data = array();

if(mysqli_num_rows($result) > 0)
{
 while($row = mysqli_fetch_assoc($result))
 {
  $data[] = $row["name"];
 }
 echo json_encode($data);
}

?>

Tuesday 18 April 2017

How to Generate Excel File in Codeigniter using PHPExcel



This tutorial has cover topic like How to export Data from Database to Excel file in Codeigniter Framework by using PHPExcel library. By using this library we can read write and create Excel file in PHP. In one of the Webslesson old post we have already discussing topic like Import and Export Mysql data to Excel in PHP by using PHPExcel Library. But now in this post we have make discussion on how to Generate excel report in Codeigniter.

We all know Excel sheet data is use by most of the ways, so if you have build an application in which you can exchange data from your system to Excel file is one of the required feature in any web application. Via Excel sheet data you can also import data in system or you can also get data from system also. So for this operation we have use PHPExcel library. By using this library we have get any amount of data from our web application.

But suppose you have make your web application in Codeigniter framework then at that time you have to follow rules of MVC framework, because Codeigniter is one of the best MVC Framework, so in this framework you can directly use this PHPExcel library in Codeigniter. So there is a one question how to generate excel file in Codeigniter. So for this we can use this library by two ways. First ways is you have make an helper in Codeigniter, that means you have to paste this library under Codeingier helper folder and make simple PDF helper and in that helper you have to make one function in which you hav to include PHPExcel Class. So Via helper you can use PHPExcel library in Codeigniter. There is one another ways also you have to make your own library also. So for make library into Codeigniter, you have to copy library file under library folder and create one new library class which extends the class of PHPExcel. So this way you can develop your own PDF library in Codeigniter Framework.

Now here we will make PDF library for use of PHPExcel library in Codeigniter, so when we want to access this library we want to just PDF library where we want to use functionality of this library. Here we have share complete required source code for How to Export HTML table to Excel in Codeigniter.






Source Code


Libraries/Excel.php



<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
require_once('PHPExcel.php');

class Excel extends PHPExcel
{
 public function __construct()
 {
  parent::__construct();
 }
}

?>


Libraries/IOFactory.php



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

require_once('PHPExcel/IOFactory.php');

class IOFactory extends PHPExcel_IOFactory
{
 public function __construct()
 {
  parent::__construct();
 }
}

?>


Controllers/Excel_export.php



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

class Excel_export extends CI_Controller {
 
 function index()
 {
  $this->load->model("excel_export_model");
  $data["employee_data"] = $this->excel_export_model->fetch_data();
  $this->load->view("excel_export_view", $data);
 }

 function action()
 {
  $this->load->model("excel_export_model");
  $this->load->library("excel");
  $object = new PHPExcel();

  $object->setActiveSheetIndex(0);

  $table_columns = array("Name", "Address", "Gender", "Designation", "Age");

  $column = 0;

  foreach($table_columns as $field)
  {
   $object->getActiveSheet()->setCellValueByColumnAndRow($column, 1, $field);
   $column++;
  }

  $employee_data = $this->excel_export_model->fetch_data();

  $excel_row = 2;

  foreach($employee_data as $row)
  {
   $object->getActiveSheet()->setCellValueByColumnAndRow(0, $excel_row, $row->name);
   $object->getActiveSheet()->setCellValueByColumnAndRow(1, $excel_row, $row->address);
   $object->getActiveSheet()->setCellValueByColumnAndRow(2, $excel_row, $row->gender);
   $object->getActiveSheet()->setCellValueByColumnAndRow(3, $excel_row, $row->designation);
   $object->getActiveSheet()->setCellValueByColumnAndRow(4, $excel_row, $row->age);
   $excel_row++;
  }

  $object_writer = PHPExcel_IOFactory::createWriter($object, 'Excel5');
  header('Content-Type: application/vnd.ms-excel');
  header('Content-Disposition: attachment;filename="Employee Data.xls"');
  $object_writer->save('php://output');
 }

 
 
}


Models/Excel_export_model.php



<?php
class Excel_export_model extends CI_Model
{
 function fetch_data()
 {
  $this->db->order_by("id", "DESC");
  $query = $this->db->get("employee");
  return $query->result();
 }

 
}



Views/excel_export_view.php



<html>
<head>
    <title>Export Data to Excel in Codeigniter using PHPExcel</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">Export Data to Excel in Codeigniter using PHPExcel</h3>
  <br />
  <div class="table-responsive">
   <table class="table table-bordered">
    <tr>
     <th>Name</th>
     <th>Address</th>
     <th>Gender</th>
     <th>Designation</th>
     <th>Age</th>
    </tr>
    <?php
    foreach($employee_data as $row)
    {
     echo '
     <tr>
      <td>'.$row->name.'</td>
      <td>'.$row->address.'</td>
      <td>'.$row->gender.'</td>
      <td>'.$row->designation.'</td>
      <td>'.$row->age.'</td>
     </tr>
     ';
    }
    ?>
   </table>
   <div align="center">
    <form method="post" action="<?php echo base_url(); ?>excel_export/action">
     <input type="submit" name="export" class="btn btn-success" value="Export" />
    </form>
   </div>
   <br />
   <br />
  </div>
 </div>
</body>
</html>

Saturday 15 April 2017

How to Submit Form with Validation in AngularJS with PHP



In this post we are going to learn How to submit form data by using AngularJS with some validation by using PHP Script. We all know how to submit form by using Ajax in JQuery. But now we will do this things by using AngularJS. In current web development there number of technology we can use to submit form. So we want know to submit by atleast some major technology which are widely used. So AngularJS is one of the highly use font end technology after JQuery. This is also manage by Google inc on their hosted library.

We have already published some of post later in which we have already make discussion on Insert Update Delete crud operation by AngularJS, How to upload file by using AngularJS and many more. But know we have learn some advance topic AngularJS. Here we will handle form data by using AngularJS and we will make required field validation by using PHP Script. We all know basic uses of AngularJS directives, event. By using this basic concept we will make simple AngularJS application in which we will make simple for Insert user data into Mysql table.

We all know while we have submit simple text form data by Jquery then at that time we have used simple serialize() method and by using this method we have convert form data into url encoded string. But in AngularJS we want to create blank object for bind form data and after this that object name we have to define into different input tag ng-model directive. So after defining object into ng-model directive then after form data has been bind into object. So when form has been submitted then form data has been bind into this form object and in PHP script we can access form field by using Object.

For display validation error message, we have use ng-show directive of AngularJS into HTML tag. The main functionality of this directive is when it has some value then that HTML element will be visible on web page otherwise it will be hidden. So this way we have use different features of AngularJS for submit form data to server with validation.







Source Code


index.php



<!DOCTYPE html>
<html>
 <head>
  <title>Webslesson Tutorial | Submit Form Data by using AngularJS with Validation using PHP</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
 </head>
 <body>
  <br /><br />
  <div class="container" style="width:750px;">
   <h3 align="center">Submit Form Data by using AngularJS with Validation using PHP</h3>
   <br /><br />
   <div ng-app="myapp" ng-controller="formcontroller">
    <form name="userForm" ng-submit="insertData()">
     <label class="text-success" ng-show="successInsert">{{successInsert}}</label>
     <div class="form-group">
      <label>First Name <span class="text-danger">*</span></label>
      <input type="text" name="first_name" ng-model="insert.first_name" class="form-control" />
      <span class="text-danger" ng-show="errorFirstname">{{errorFirstname}}</span>
     </div>
     <div class="form-group">
      <label>Last Name <span class="text-danger">*</span></label>
      <input type="text" name="last_name" ng-model="insert.last_name" class="form-control" />
      <span class="text-danger" ng-show="errorLastname">{{errorLastname}}</span>
     </div>
     <br />
     <div class="form-group">
      <input type="submit" name="insert" class="btn btn-info" value="Insert"/>
     </div>
    </form>
   </div>
  </div>
 </body>
</html>



<script>
var application = angular.module("myapp", []);
application.controller("formcontroller", function($scope, $http){
 $scope.insert = {};
 $scope.insertData = function(){
  $http({
   method:"POST",
   url:"insert.php",
   data:$scope.insert,
  }).success(function(data){
   if(data.error)
   {
    $scope.errorFirstname = data.error.first_name;
    $scope.errorLastname = data.error.last_name;
    $scope.successInsert = null;
   }
   else
   {
    $scope.insert = null;
    $scope.errorFirstname = null;
    $scope.errorLastname = null;
    $scope.successInsert = data.message;
   }
  });
 }
});
</script>


insert.php



<?php
//insert.php
$connect = mysqli_connect("localhost", "root", "", "testing");
$form_data = json_decode(file_get_contents("php://input"));
$data = array();
$error = array();

if(empty($form_data->first_name))
{
 $error["first_name"] = "First Name is required";
}

if(empty($form_data->last_name))
{
 $error["last_name"] = "Last Name is required";
}

if(!empty($error))
{
 $data["error"] = $error;
}
else
{
 $first_name = mysqli_real_escape_string($connect, $form_data->first_name); 
 $last_name = mysqli_real_escape_string($connect, $form_data->last_name);
 $query = "
  INSERT INTO tbl_user(first_name, last_name) VALUES ('$first_name', '$last_name')
 ";
 if(mysqli_query($connect, $query))
 {
  $data["message"] = "Data Inserted...";
 }
}

echo json_encode($data);

?>



--
-- Database: `testing`
--

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

--
-- Table structure for table `tbl_user`
--

CREATE TABLE IF NOT EXISTS `tbl_user` (
  `id` int(11) NOT NULL,
  `first_name` varchar(250) NOT NULL,
  `last_name` varchar(250) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_user`
--

INSERT INTO `tbl_user` (`id`, `first_name`, `last_name`) VALUES
(1, 'Peter', 'Parker'),
(2, 'John', 'Smith'),
(3, 'Kevin', 'Peterson');

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

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

Wednesday 12 April 2017

Create Live Donut Chart by using Morris.js with Ajax PHP



If you are looking for Morris.js chart tutorial with Ajax PHP and Mysql then in you can find from this post. In this post we have make Live Donut Chart by using Morris.js Chart library with Ajax PHP and Mysql. Here Live chart means chart will display live data from Mysql database without refresh of webpage. We all know Morris.js chart library is very popular graph library to display data in chart format on web page and most of the programmer use this library for display data in graphic format on web page.

In our one of the previous web tutorial we have already seen how to use Morris.js chart library with simple PHP script and Mysql database and in that post we have seen Area chart, Bar chart and Line chart. So in this post we will seen Donut chart from Morris.js library. But this time we have use Ajax for make live data chart, that means when we have enter data into table then that data will be updated on chart without refresh of webpage.

For understand this topic we have take an example of popularity of PHP framework, for this things we have make simple form with selection of one framework from five different framework. When user will select his favorite framework from list and click on like button then his framework like dat will be inserted into table. For insert data we have use Ajax request, so when Ajax request has been successfully completed then we have fetch data from table and after this we have use Morris.js chart library setData() method, by using this method we can update chart data without refresh of web page. In this method we have required data in JSON format then this method can update chart data. So this way we have Create simple Live data Donut Chart by using Morris.js Chart library with Ajax PHP and Mysql.








Source Code


index.php



<?php 
//index.php
$connect = mysqli_connect("localhost", "root", "", "testing");
$sub_query = "
   SELECT framework, count(*) as no_of_like FROM like_table 
   GROUP BY framework 
   ORDER BY id ASC";
$result = mysqli_query($connect, $sub_query);
$data = array();
while($row = mysqli_fetch_array($result))
{
 $data[] = array(
  'label'  => $row["framework"],
  'value'  => $row["no_of_like"]
 );
}
$data = json_encode($data);
?>


<!DOCTYPE html>
<html>
 <head>
  <title>Webslesson Tutorial | Live Donut Chart by using Morris.js with Ajax PHP</title>  
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/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>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css" />  
 </head>
 <body>
  <br /><br />
  <div class="container" style="width:900px;">
   <h2 align="center">Live Donut Chart by using Morris.js with Ajax PHP</h2>
   <form method="post" id="like_form">
    <div class="form-group">
     <label>Like Any one PHP Framework</label>
     <div class="radio">
      <label><input type="radio" name="framework" value="Codeigniter" /> Codeigniter</label>
     </div>
     <div class="radio">
      <label><input type="radio" name="framework" value="Laravel" /> Laravel</label>
     </div>
     <div class="radio">
      <label><input type="radio" name="framework" value="Symfony" /> Symfony</label>
     </div>
     <div class="radio">
      <label><input type="radio" name="framework" value="Yii" /> Yii</label>
     </div>
     <div class="radio">
      <label><input type="radio" name="framework" value="CakePHP" /> CakePHP</label>
     </div>
    </div>
    <div class="form-group">
     <input type="submit" name="like" class="btn btn-info" value="Like" />
    </div>
   </form>
   <div id="chart"></div>
  </div>
 </body>
</html>

<script>

$(document).ready(function(){
 
 var donut_chart = Morris.Donut({
     element: 'chart',
     data: <?php echo $data; ?>
    });
  
 $('#like_form').on('submit', function(event){
  event.preventDefault();
  var checked = $('input[name=framework]:checked', '#like_form').val();
  if(checked == undefined)
  {
   alert("Please Like any Framework");
   return false;
  }
  else
  {
   var form_data = $(this).serialize();
   $.ajax({
    url:"action.php",
    method:"POST",
    data:form_data,
    dataType:"json",
    success:function(data)
    {
     $('#like_form')[0].reset();
     donut_chart.setData(data);
    }
   });
  }
 });
});

</script>


action.php



<?php
//action.php
$connect = mysqli_connect("localhost", "root", "", "testing");
if(isset($_POST["framework"]))
{
 $query = "
  INSERT INTO like_table(framework) VALUES('".$_POST["framework"]."')
 ";
 mysqli_query($connect, $query);
 $sub_query = "
   SELECT framework, count(*) as no_of_like FROM like_table 
   GROUP BY framework 
   ORDER BY id ASC";
 $result = mysqli_query($connect, $sub_query);
 $data = array();
 while($row = mysqli_fetch_array($result))
 {
  $data[] = array(
   'label'  => $row["framework"],
   'value'  => $row["no_of_like"]
  );
 }
 $data = json_encode($data);
 echo $data;
}
?>


Database



--
-- Database: `testing`
--

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

--
-- Table structure for table `like_table`
--

CREATE TABLE IF NOT EXISTS `like_table` (
  `id` int(11) NOT NULL,
  `framework` varchar(100) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=45 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `like_table`
--

INSERT INTO `like_table` (`id`, `framework`) VALUES
(2, 'Laravel'),
(3, 'Symfony'),
(4, 'Yii'),
(5, 'CakePHP'),
(6, 'Codeigniter'),
(7, 'Codeigniter'),
(8, 'Laravel'),
(9, 'Yii'),
(10, 'Codeigniter'),
(11, 'Laravel'),
(12, 'Symfony'),
(13, 'Codeigniter'),
(14, 'Yii'),
(15, 'Codeigniter'),
(16, 'CakePHP'),
(17, 'Yii'),
(18, 'Codeigniter'),
(19, 'Laravel'),
(20, 'Laravel'),
(21, 'Laravel'),
(22, 'Laravel'),
(23, 'Codeigniter'),
(24, 'Codeigniter'),
(25, 'Codeigniter'),
(26, 'CakePHP'),
(27, 'CakePHP'),
(28, 'Codeigniter'),
(29, 'Laravel'),
(30, 'Symfony'),
(31, 'Yii'),
(32, 'Codeigniter'),
(33, 'Codeigniter'),
(34, 'Laravel'),
(35, 'Symfony'),
(36, 'Yii'),
(37, 'CakePHP'),
(38, 'Codeigniter'),
(39, 'Codeigniter'),
(40, 'Codeigniter'),
(41, 'Codeigniter'),
(42, 'CakePHP'),
(43, 'Laravel'),
(44, 'Symfony');

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

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

Monday 10 April 2017

Convert HTML to PDF in PHP using Dompdf



In this post we have seen one more PHP PDF converter library, here we will make discussion on Dompdf library which are used to convert HTML to PDF document. So in this blog we will check how to use Dompdf library with PHP Script to generate PDF document from HTML. First time PDF document was introduced by Adobe as fixed layout document. This type of document is used for download large amount of data in document format from dynamic website. When we have download document from website then at that time PDF document has been made from HTML that means it will convert HTML to PDF. So here we will seen How to convert HTML to PDF by using Dompdf library with PHP Script.

Dompdf library used to make dynamic PDF document in your web application which are completely based on PHP language. This library will directly display HTML and CSS data in PDF format on web browser or it can directly push to download PDF document. Dompdf library is usually used for convert HTML data to PDF document. If you have build any dynamic web application and you have to provide report in PDF format then we have to suggest go for Dompdf library for making dynamic PDF document from web application. By using this library we can easily convert HTML data to fixed layout document format like PDF.



If you want to use Dompdf library for convert HTML to PDF, then you can download latest version of this library from this link of GitHub. If you have download latest version of this library then you do not want to download other PHP library like PHP Font library and PHP SVG Library. Both library will come with latest version. You can find complete guide to how to use Dompdf library from below source.




Source Code



<?php
//index.php
//include autoloader

require_once 'dompdf/autoload.inc.php';

// reference the Dompdf namespace

use Dompdf\Dompdf;

//initialize dompdf class

$document = new Dompdf();

$html = '
 <style>
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}

tr:nth-child(even) {
    background-color: #dddddd;
}
</style>
<table>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
</table>
';

//$document->loadHtml($html);
$page = file_get_contents("cat.html");

//$document->loadHtml($page);

$connect = mysqli_connect("localhost", "root", "", "testing1");

$query = "
 SELECT category.category_name, product.product_name, product.product_price
 FROM product 
 INNER JOIN category 
 ON category.category_id = product.category_id
";
$result = mysqli_query($connect, $query);

$output = "
 <style>
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}

tr:nth-child(even) {
    background-color: #dddddd;
}
</style>
<table>
 <tr>
  <th>Category</th>
  <th>Product Name</th>
  <th>Price</th>
 </tr>
";

while($row = mysqli_fetch_array($result))
{
 $output .= '
  <tr>
   <td>'.$row["category_name"].'</td>
   <td>'.$row["product_name"].'</td>
   <td>$'.$row["product_price"].'</td>
  </tr>
 ';
}

$output .= '</table>';

//echo $output;

$document->loadHtml($output);

//set page size and orientation

$document->setPaper('A4', 'landscape');

//Render the HTML as PDF

$document->render();

//Get output of generated pdf in Browser

$document->stream("Webslesson", array("Attachment"=>0));
//1  = Download
//0 = Preview


?>

Thursday 6 April 2017

Jquery Bootgrid - Server Side Processing using Ajax PHP

If you have know Jquery Bootgrid Plugin is extremely accepted html table grid plugin and mainly developed for Bootstrap. So we can easily integrate this Bootgrid plugin with Bootstrap framework. In this post we will discussing on how can we do server side processing with Bootgrid plugin by using PHP Ajax. This post helps you to do server side operation like fetch or select of data from table with all Bootgrid plugin functionality like searching table data, pagination, column sorting and many more. We will also see how to add or insert data into mysql table by using PHP Ajax and load inserted data on Bootgrid plugin, how to edit or update Bootgrid table data by using PHP with Ajax and Bootstrap modal and lastly we will also learn how to remove or delete data from Bootgrid data and display available data on Web page under Bootgrid table.

Bootgrid is extremely well build jquery grid plugin that is used to change a simple HTML table into powerful grid with extra ordinary functionality like table column sorting, pagination, searching table data from server side, and insert, update and delete records features. We will learn following functionality of Bootgrid plugin by using PHP Mysql and Ajax.

  • Listing data on Bootgrid using Ajax and PHP
  • Bootgrid Searching Table data with Server side processing using PHP with Ajax
  • Bootgrid Server Side Pagination
  • Bootgrid table column sorting
  • Add Edit and Delete Button under Bootgrid table
  • Insert or Add data using Bootstrap modal with Ajax and PHP
  • Edit or Update data using Bootstrap modal with Ajax and PHP
  • Delete data with Confirmation message using Ajax with PHP






So, In this post we will simply combine two table data by using Inner join query and after this we have put certain condition if Bootgrid send request for searching of data then we have put search data query condition at server side, if Bootgrid plugin send request for sorting of data then at server side we have put condition for sorting of data and many more.

In Jquery Bootgrid plugin we can not fire jquery click event on button, so for this we have load Bootgrid constructor for this, after loading Bootgrid constructor we can fire click event on Edit and delete button and after this we have send ajax request for edit or delete of data at server side. So this way we have perform all Bootgrid operation at server side by using Ajax PHP.



Source Code


index.php



<?php
include("connection.php");
$query = "SELECT * FROM category";
$result = mysqli_query($connection, $query);
$output = '';
while($row = mysqli_fetch_array($result))
{
 $output .= '<option value="'.$row["category_id"].'">'.$row["category_name"].'</option>';
}
?>
<html>
 <head>
  <title>Bootgrid Tutorial - Server Side Processing using Ajax PHP</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-bootgrid/1.3.1/jquery.bootgrid.css" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> 
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-bootgrid/1.3.1/jquery.bootgrid.js"></script>  
  <style>
   body
   {
    margin:0;
    padding:0;
    background-color:#f1f1f1;
   }
   .box
   {
    width:1270px;
    padding:20px;
    background-color:#fff;
    border:1px solid #ccc;
    border-radius:5px;
    margin-top:25px;
   }
  </style>
 </head>
 <body>
  <div class="container box">
   <h1 align="center">Jquery Bootgrid Tutorial - Server Side Processing using Ajax PHP</h1>
   <br />
   <div align="right">
    <button type="button" id="add_button" data-toggle="modal" data-target="#productModal" class="btn btn-info btn-lg">Add</button>
   </div>
   <div class="table-responsive">
    <table id="product_data" class="table table-bordered table-striped">
     <thead>
      <tr>
       <th data-column-id="product_id" data-type="numeric">ID</th>
       <th data-column-id="product_name">Product Name</th>
       <th data-column-id="category_name">Category</th>
       <th data-column-id="product_price">Price</th>
       <th data-column-id="commands" data-formatter="commands" data-sortable="false">Commands</th>
      </tr>
     </thead>
    </table>
   </div>
 </body>
</html>
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
 $('#add_button').click(function(){
  $('#product_form')[0].reset();
  $('.modal-title').text("Add Product");
  $('#action').val("Add");
  $('#operation').val("Add");
 });
 
 var productTable = $('#product_data').bootgrid({
  ajax: true,
  rowSelect: true,
  post: function()
  {
   return{
    id: "b0df282a-0d67-40e5-8558-c9e93b7befed"
   };
  },
  url: "fetch.php",
  formatters: {
   "commands": function(column, row)
   {
    return "<button type='button' class='btn btn-warning btn-xs update' data-row-id='"+row.product_id+"'>Edit</button>" + 
    "&nbsp; <button type='button' class='btn btn-danger btn-xs delete' data-row-id='"+row.product_id+"'>Delete</button>";
   }
  }
 });
 
 $(document).on('submit', '#product_form', function(event){
  event.preventDefault();
  var category_id = $('#category_id').val();
  var product_name = $('#product_name').val();
  var product_price = $('#product_price').val();
  var form_data = $(this).serialize();
  if(category_id != '' && product_name != '' && product_price != '')
  {
   $.ajax({
    url:"insert.php",
    method:"POST",
    data:form_data,
    success:function(data)
    {
     alert(data);
     $('#product_form')[0].reset();
     $('#productModal').modal('hide');
     $('#product_data').bootgrid('reload');
    }
   });
  }
  else
  {
   alert("All Fields are Required");
  }
 });
 
 $(document).on("loaded.rs.jquery.bootgrid", function()
 {
  productTable.find(".update").on("click", function(event)
  {
   var product_id = $(this).data("row-id");
    $.ajax({
    url:"fetch_single.php",
    method:"POST",
    data:{product_id:product_id},
    dataType:"json",
    success:function(data)
    {
     $('#productModal').modal('show');
     $('#category_id').val(data.category_id);
     $('#product_name').val(data.product_name);
     $('#product_price').val(data.product_price);
     $('.modal-title').text("Edit Product");
     $('#product_id').val(product_id);
     $('#action').val("Edit");
     $('#operation').val("Edit");
    }
   });
  });
 });
 
 $(document).on("loaded.rs.jquery.bootgrid", function()
 {
  productTable.find(".delete").on("click", function(event)
  {
   if(confirm("Are you sure you want to delete this?"))
   {
    var product_id = $(this).data("row-id");
    $.ajax({
     url:"delete.php",
     method:"POST",
     data:{product_id:product_id},
     success:function(data)
     {
      alert(data);
      $('#product_data').bootgrid('reload');
     }
    })
   }
   else{
    return false;
   }
  });
 }); 
});
</script>
<div id="productModal" class="modal fade">
 <div class="modal-dialog">
  <form method="post" id="product_form">
   <div class="modal-content">
    <div class="modal-header">
     <button type="button" class="close" data-dismiss="modal">&times;</button>
     <h4 class="modal-title">Add Product</h4>
    </div>
    <div class="modal-body">
     <label>Select Category</label>
     <select name="category_id" id="category_id" class="form-control">
      <option value="">Select Category</option>
      <?php echo $output; ?>
     </select>
     <br />
     <label>Enter Product Name</label>
     <input type="text" name="product_name" id="product_name" class="form-control" />
     <br />
     <label>Enter Product Price</label>
     <input type="text" name="product_price" id="product_price" class="form-control" />
    </div>
    <div class="modal-footer">
     <input type="hidden" name="product_id" id="product_id" />
     <input type="hidden" name="operation" id="operation" />
     <input type="submit" name="action" id="action" class="btn btn-success" value="Add" />
    </div>
   </div>
  </form>
 </div>
</div>


connection.php



<?php
//database.php
$connection = mysqli_connect("localhost", "root", "", "testing1");
?>


fetch.php



<?php
//fetch.php
include("connection.php");
$query = '';
$data = array();
$records_per_page = 10;
$start_from = 0;
$current_page_number = 0;
if(isset($_POST["rowCount"]))
{
 $records_per_page = $_POST["rowCount"];
}
else
{
 $records_per_page = 10;
}
if(isset($_POST["current"]))
{
 $current_page_number = $_POST["current"];
}
else
{
 $current_page_number = 1;
}
$start_from = ($current_page_number - 1) * $records_per_page;
$query .= "
 SELECT 
  product.product_id, 
  category.category_name, 
  product.product_name, 
  product.product_price FROM product 
  INNER JOIN category 
  ON category.category_id = product.category_id ";
if(!empty($_POST["searchPhrase"]))
{
 $query .= 'WHERE (product.product_id LIKE "%'.$_POST["searchPhrase"].'%" ';
 $query .= 'OR category.category_name LIKE "%'.$_POST["searchPhrase"].'%" ';
 $query .= 'OR product.product_name LIKE "%'.$_POST["searchPhrase"].'%" ';
 $query .= 'OR product.product_price LIKE "%'.$_POST["searchPhrase"].'%" ) ';
}
$order_by = '';
if(isset($_POST["sort"]) && is_array($_POST["sort"]))
{
 foreach($_POST["sort"] as $key => $value)
 {
  $order_by .= " $key $value, ";
 }
}
else
{
 $query .= 'ORDER BY product.product_id DESC ';
}
if($order_by != '')
{
 $query .= ' ORDER BY ' . substr($order_by, 0, -2);
}

if($records_per_page != -1)
{
 $query .= " LIMIT " . $start_from . ", " . $records_per_page;
}
//echo $query;
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result))
{
 $data[] = $row;
}

$query1 = "SELECT * FROM product";
$result1 = mysqli_query($connection, $query1);
$total_records = mysqli_num_rows($result1);

$output = array(
 'current'  => intval($_POST["current"]),
 'rowCount'  => 10,
 'total'   => intval($total_records),
 'rows'   => $data
);

echo json_encode($output);

?>


insert.php



<?php
//insert.php
include("connection.php");
if(isset($_POST["operation"]))
{
 if($_POST["operation"] == "Add")
 {
  $category_id = mysqli_real_escape_string($connection, $_POST["category_id"]);
  $product_name = mysqli_real_escape_string($connection, $_POST["product_name"]);
  $product_price = mysqli_real_escape_string($connection, $_POST["product_price"]);
  $query = "
   INSERT INTO product(category_id, product_name, product_price) 
   VALUES ('".$category_id."', '".$product_name."', '".$product_price."')
  ";
  if(mysqli_query($connection, $query))
  {
   echo 'Product Inserted';
  }
 }
 if($_POST["operation"] == "Edit")
 {
  $category_id = mysqli_real_escape_string($connection, $_POST["category_id"]);
  $product_name = mysqli_real_escape_string($connection, $_POST["product_name"]);
  $product_price = mysqli_real_escape_string($connection, $_POST["product_price"]);
  $query = "
   UPDATE product 
   SET category_id = '".$category_id."', 
   product_name = '".$product_name."', 
   product_price = '".$product_price."' 
   WHERE product_id = '".$_POST["product_id"]."'
  ";
  if(mysqli_query($connection, $query))
  {
   echo 'Product Updated';
  }
 }
}
?>


fetch_single.php



<?php
//fetch_single.php
include("connection.php");
if(isset($_POST["product_id"]))
{
 //$output = array();
 $query = "SELECT * FROM product WHERE product_id = '".$_POST["product_id"]."'";
 $result = mysqli_query($connection, $query);
 while($row = mysqli_fetch_array($result))
 {
  $output["category_id"] = $row["category_id"];
  $output["product_name"] = $row["product_name"];
  $output["product_price"] = $row["product_price"];
 }
 echo json_encode($output);
}

?>


delete.php



<?php
//delete.php
include("connection.php");
if(isset($_POST["product_id"]))
{
 $query = "DELETE FROM product WHERE product_id = '".$_POST["product_id"]."'";
 if(mysqli_query($connection, $query))
 {
  echo 'Data Deleted';
 }
}
?>


Database



--
-- Database: `testing1`
--

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

--
-- Table structure for table `category`
--

CREATE TABLE IF NOT EXISTS `category` (
  `category_id` int(11) NOT NULL,
  `category_name` varchar(250) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `category`
--

INSERT INTO `category` (`category_id`, `category_name`) VALUES
(1, 'Electronics & Computers'),
(2, 'Home, Garden & Tools'),
(3, 'Handmade');

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

--
-- 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=14 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');

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

--
-- Indexes for table `category`
--
ALTER TABLE `category`
  ADD PRIMARY KEY (`category_id`);

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

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `category`
--
ALTER TABLE `category`
  MODIFY `category_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `product`
--
ALTER TABLE `product`
  MODIFY `product_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=14;

Saturday 1 April 2017

Inline Edit data by using X-editable with PHP and Mysql



If you looking for web tutorial on X-editable jquery plugin, then you have come on right place in this post we have make discussion on how to live update or edit of mysql table data by using X-editable jquery plugin as front-end and as back-end we have use PHP script. We will make simple inline table edit of data by using X-editable with PHP. We have received many request from our readers so we have make this type of tutorial.

In this post we will inline edit of data with X-editable with PHP and Mysql. Live Inline updating of data is extremely required functionality of website that will authorize user can edit without going to other pages. In this you can edit single column data at one time. There are many inline editing plugin available but we have use X-editable plugin that make html element editable inline.



First we have include following links in our index page.


<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
  <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script> 
  <script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.1/bootstrap3-editable/css/bootstrap-editable.css" rel="stylesheet">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.1/bootstrap3-editable/js/bootstrap-editable.js"></script>


Thenafter we have define simple html table, we will load data under this table.


<table class="table table-bordered table-striped">
    <thead>
     <tr>
      <th width="10%">ID</th>
      <th width="40%">Name</th>
      <th width="10%">Gender</th>
      <th width="30%">Designation</th>
      <th width="10%">Age</th>
     </tr>
    </thead>
    <tbody id="employee_data">
    </tbody>
   </table>


We have make this jquery function which fetch data from table and display under above table.


function fetch_employee_data()
 {
  $.ajax({
   url:"fetch.php",
   method:"POST",
   dataType:"json",
   success:function(data)
   {
    for(var count=0; count<data.length; count++)
    {
     var html_data = '<tr><td>'+data[count].id+'</td>';
     html_data += '<td data-name="name" class="name" data-type="text" data-pk="'+data[count].id+'">'+data[count].name+'</td>';
     html_data += '<td data-name="gender" class="gender" data-type="select" data-pk="'+data[count].id+'">'+data[count].gender+'</td>';
     html_data += '<td data-name="designation" class="designation" data-type="text" data-pk="'+data[count].id+'">'+data[count].designation+'</td>';
     html_data += '<td data-name="age" class="age" data-type="text" data-pk="'+data[count].id+'">'+data[count].age+'</td></tr>';
     $('#employee_data').append(html_data);
    }
   }
  })
 }


We have write this php code that received request from Ajax and fetch data from table and send back data to Ajax request.


<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "testing");
$query = "SELECT * FROM employee";
$result = mysqli_query($connect, $query);
$output = array();
while($row = mysqli_fetch_assoc($result))
{
 $output[] = $row;
}
echo json_encode($output);
?>


Now we want to make table column editable by using this editable method, here we have make editable table column like name, gender, designation and age table column. We have also put validation like required field for all column and we have also use number only validation for age table column also. We have also make select box in gender table column also. This all feature we have use by using this X-editable plugin. Here we have send ajax request for update of data to update.php page. This way it will update particular table column data by using X-editable plugin.


$('#employee_data').editable({
  container: 'body',
  selector: 'td.name',
  url: "update.php",
  title: 'Employee Name',
  type: "POST",
  //dataType: 'json',
  validate: function(value){
   if($.trim(value) == '')
   {
    return 'This field is required';
   }
  }
 });
 
 $('#employee_data').editable({
  container: 'body',
  selector: 'td.gender',
  url: "update.php",
  title: 'Gender',
  type: "POST",
  dataType: 'json',
  source: [{value: "Male", text: "Male"}, {value: "Female", text: "Female"}],
  validate: function(value){
   if($.trim(value) == '')
   {
    return 'This field is required';
   }
  }
 });
 
 $('#employee_data').editable({
  container: 'body',
  selector: 'td.designation',
  url: "update.php",
  title: 'Designation',
  type: "POST",
  dataType: 'json',
  validate: function(value){
   if($.trim(value) == '')
   {
    return 'This field is required';
   }
  }
 });
 
 $('#employee_data').editable({
  container: 'body',
  selector: 'td.age',
  url: "update.php",
  title: 'Age',
  type: "POST",
  dataType: 'json',
  validate: function(value){
   if($.trim(value) == '')
   {
    return 'This field is required';
   }
   var regex = /^[0-9]+$/;
   if(! expression.test(value))
   {
    return 'Numbers only!';
   }
  }
 });


Lastly, this PHP code will update particular table column data as per it received ajax request with data.


<?php
//update.php
$connect = mysqli_connect("localhost", "root", "", "testing");
$query = "
 UPDATE employee SET ".$_POST["name"]." = '".$_POST["value"]."' 
 WHERE id = '".$_POST["pk"]."'";
mysqli_query($connect, $query);
?>


Source Code


index.php



<html>
 <head>
  <title>Live Inline Update data using X-editable with PHP and Mysql</title>
  <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
  <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script> 
  <script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.1/bootstrap3-editable/css/bootstrap-editable.css" rel="stylesheet">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.1/bootstrap3-editable/js/bootstrap-editable.js"></script>
  
 </head>
 <body>
  <div class="container">
   <h1 align="center">Live Inline Update data using X-editable with PHP and Mysql</h1>
   <br />
   <table class="table table-bordered table-striped">
    <thead>
     <tr>
      <th width="10%">ID</th>
      <th width="40%">Name</th>
      <th width="10%">Gender</th>
      <th width="30%">Designation</th>
      <th width="10%">Age</th>
     </tr>
    </thead>
    <tbody id="employee_data">
    </tbody>
   </table>
 </body>
</html>



<script type="text/javascript" language="javascript" >
$(document).ready(function(){
 
 function fetch_employee_data()
 {
  $.ajax({
   url:"fetch.php",
   method:"POST",
   dataType:"json",
   success:function(data)
   {
    for(var count=0; count<data.length; count++)
    {
     var html_data = '<tr><td>'+data[count].id+'</td>';
     html_data += '<td data-name="name" class="name" data-type="text" data-pk="'+data[count].id+'">'+data[count].name+'</td>';
     html_data += '<td data-name="gender" class="gender" data-type="select" data-pk="'+data[count].id+'">'+data[count].gender+'</td>';
     html_data += '<td data-name="designation" class="designation" data-type="text" data-pk="'+data[count].id+'">'+data[count].designation+'</td>';
     html_data += '<td data-name="age" class="age" data-type="text" data-pk="'+data[count].id+'">'+data[count].age+'</td></tr>';
     $('#employee_data').append(html_data);
    }
   }
  })
 }
 
 fetch_employee_data();
 
 $('#employee_data').editable({
  container: 'body',
  selector: 'td.name',
  url: "update.php",
  title: 'Employee Name',
  type: "POST",
  //dataType: 'json',
  validate: function(value){
   if($.trim(value) == '')
   {
    return 'This field is required';
   }
  }
 });
 
 $('#employee_data').editable({
  container: 'body',
  selector: 'td.gender',
  url: "update.php",
  title: 'Gender',
  type: "POST",
  dataType: 'json',
  source: [{value: "Male", text: "Male"}, {value: "Female", text: "Female"}],
  validate: function(value){
   if($.trim(value) == '')
   {
    return 'This field is required';
   }
  }
 });
 
 $('#employee_data').editable({
  container: 'body',
  selector: 'td.designation',
  url: "update.php",
  title: 'Designation',
  type: "POST",
  dataType: 'json',
  validate: function(value){
   if($.trim(value) == '')
   {
    return 'This field is required';
   }
  }
 });
 
 $('#employee_data').editable({
  container: 'body',
  selector: 'td.age',
  url: "update.php",
  title: 'Age',
  type: "POST",
  dataType: 'json',
  validate: function(value){
   if($.trim(value) == '')
   {
    return 'This field is required';
   }
   var regex = /^[0-9]+$/;
   if(! expression.test(value))
   {
    return 'Numbers only!';
   }
  }
 });
 
 
 
});
</script>


fetch.php



<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "testing");
$query = "SELECT * FROM employee";
$result = mysqli_query($connect, $query);
$output = array();
while($row = mysqli_fetch_assoc($result))
{
 $output[] = $row;
}
echo json_encode($output);
?>


update.php



<?php
//update.php
$connect = mysqli_connect("localhost", "root", "", "testing");
$query = "
 UPDATE employee SET ".$_POST["name"]." = '".$_POST["value"]."' 
 WHERE id = '".$_POST["pk"]."'";
mysqli_query($connect, $query);
?>