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;