Wednesday, 7 December 2016

Codeigniter Ajax Crud using DataTables - Insert / Add Data



In this post we will discussing on how can we insert data using Ajax in Codeigniter. This is one more video on Codeigniter ajax crud opearation with DataTables. In previous we have seen how can we load into DataTables by using Ajax Server side processing in Codeigniter Framework. But In this part we will Insert or Add data into Mysql database table in Codeigniter Application by using Ajax. So we can Insert data into database without page refresh. For Inserting or Adding data we have use Bootstrap Modals, we will implement form under Bootstrap Modals and this modal will be initialize by clicking button and then after we can fill form data and insert data into database by using Ajax request. After inserting or adding data into table then after we will update data of DataTables. So we will insert data using Ajax request in Codeigniter application and display that data on data table without page refresh.

You have already know how can we use Ajax for insert data in simple php script but in Codeigniter framework we have to follow the rules for Modal view controller pattern. Here according to modal view controller pattern, Ajax will send request for Insert data from view to controller and controller will send request for insert data to modal and modal will insert data and again send request to controller and controller again send request to view page and on that page we have display updated data in Data tables table by using DataTables reload method. We have use new form data object for sending form data to server in Ajax request.




Source Code


Controllers - crud.php


 <?php  
 defined('BASEPATH') OR exit('No direct script access allowed');  
 class Crud extends CI_Controller {  
      //functions  
      function index(){  
           $data["title"] = "Codeigniter Ajax CRUD with Data Tables and Bootstrap Modals";  
           $this->load->view('crud_view', $data);  
      }  
      function fetch_user(){  
           $this->load->model("crud_model");  
           $fetch_data = $this->crud_model->make_datatables();  
           $data = array();  
           foreach($fetch_data as $row)  
           {  
                $sub_array = array();  
                $sub_array[] = '<img src="'.base_url().'upload/'.$row->image.'" class="img-thumbnail" width="50" height="35" />';  
                $sub_array[] = $row->first_name;  
                $sub_array[] = $row->last_name;  
                $sub_array[] = '<button type="button" name="update" id="'.$row->id.'" class="btn btn-warning btn-xs">Update</button>';  
                $sub_array[] = '<button type="button" name="delete" id="'.$row->id.'" class="btn btn-danger btn-xs">Delete</button>';  
                $data[] = $sub_array;  
           }  
           $output = array(  
                "draw"                    =>     intval($_POST["draw"]),  
                "recordsTotal"          =>      $this->crud_model->get_all_data(),  
                "recordsFiltered"     =>     $this->crud_model->get_filtered_data(),  
                "data"                    =>     $data  
           );  
           echo json_encode($output);  
      }  
      function user_action(){  
           if($_POST["action"] == "Add")  
           {  
                $insert_data = array(  
                     'first_name'          =>     $this->input->post('first_name'),  
                     'last_name'               =>     $this->input->post("last_name"),  
                     'image'                    =>     $this->upload_image()  
                );  
                $this->load->model('crud_model');  
                $this->crud_model->insert_crud($insert_data);  
                echo 'Data Inserted';  
           }  
      }  
      function upload_image()  
      {  
           if(isset($_FILES["user_image"]))  
           {  
                $extension = explode('.', $_FILES['user_image']['name']);  
                $new_name = rand() . '.' . $extension[1];  
                $destination = './upload/' . $new_name;  
                move_uploaded_file($_FILES['user_image']['tmp_name'], $destination);  
                return $new_name;  
           }  
      }  
 }  

crud_model.php


 <?php  
 class Crud_model extends CI_Model  
 {  
      var $table = "users";  
      var $select_column = array("id", "first_name", "last_name", "image");  
      var $order_column = array(null, "first_name", "last_name", null, null);  
      function make_query()  
      {  
           $this->db->select($this->select_column);  
           $this->db->from($this->table);  
           if(isset($_POST["search"]["value"]))  
           {  
                $this->db->like("first_name", $_POST["search"]["value"]);  
                $this->db->or_like("last_name", $_POST["search"]["value"]);  
           }  
           if(isset($_POST["order"]))  
           {  
                $this->db->order_by($this->order_column[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);  
           }  
           else  
           {  
                $this->db->order_by('id', 'DESC');  
           }  
      }  
      function make_datatables(){  
           $this->make_query();  
           if($_POST["length"] != -1)  
           {  
                $this->db->limit($_POST['length'], $_POST['start']);  
           }  
           $query = $this->db->get();  
           return $query->result();  
      }  
      function get_filtered_data(){  
           $this->make_query();  
           $query = $this->db->get();  
           return $query->num_rows();  
      }       
      function get_all_data()  
      {  
           $this->db->select("*");  
           $this->db->from($this->table);  
           return $this->db->count_all_results();  
      }  
      function insert_crud($data)  
      {  
           $this->db->insert('users', $data);  
      }  
 }  

crud_view.php


 <html>  
 <head>  
   <title><?php echo $title; ?></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://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>  
      <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>            
      <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />  
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
   <style>  
           body  
           {  
                margin:0;  
                padding:0;  
                background-color:#f1f1f1;  
           }  
           .box  
           {  
                width:900px;  
                padding:20px;  
                background-color:#fff;  
                border:1px solid #ccc;  
                border-radius:5px;  
                margin-top:10px;  
           }  
      </style>  
 </head>  
 <body>  
      <div class="container box">  
           <h3 align="center"><?php echo $title; ?></h3><br />  
           <div class="table-responsive">  
                <br />  
                <button type="button" data-toggle="modal" data-target="#userModal" class="btn btn-info btn-lg">Add</button>  
                <br /><br />  
                <table id="user_data" class="table table-bordered table-striped">  
                     <thead>  
                          <tr>  
                               <th width="10%">Image</th>  
                               <th width="35%">First Name</th>  
                               <th width="35%">Last Name</th>  
                               <th width="10%">Edit</th>  
                               <th width="10%">Delete</th>  
                          </tr>  
                     </thead>  
                </table>  
           </div>  
      </div>  
 </body>  
 </html>  
 <div id="userModal" class="modal fade">  
      <div class="modal-dialog">  
           <form method="post" id="user_form">  
                <div class="modal-content">  
                     <div class="modal-header">  
                          <button type="button" class="close" data-dismiss="modal">&times;</button>  
                          <h4 class="modal-title">Add User</h4>  
                     </div>  
                     <div class="modal-body">  
                          <label>Enter First Name</label>  
                          <input type="text" name="first_name" id="first_name" class="form-control" />  
                          <br />  
                          <label>Enter Last Name</label>  
                          <input type="text" name="last_name" id="last_name" class="form-control" />  
                          <br />  
                          <label>Select User Image</label>  
                          <input type="file" name="user_image" id="user_image" />  
                     </div>  
                     <div class="modal-footer">  
                          <input type="submit" name="action" class="btn btn-success" value="Add" />  
                          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>  
                     </div>  
                </div>  
           </form>  
      </div>  
 </div>  
 <script type="text/javascript" language="javascript" >  
 $(document).ready(function(){  
      var dataTable = $('#user_data').DataTable({  
           "processing":true,  
           "serverSide":true,  
           "order":[],  
           "ajax":{  
                url:"<?php echo base_url() . 'crud/fetch_user'; ?>",  
                type:"POST"  
           },  
           "columnDefs":[  
                {  
                     "targets":[0, 3, 4],  
                     "orderable":false,  
                },  
           ],  
      });  
      $(document).on('submit', '#user_form', function(event){  
           event.preventDefault();  
           var firstName = $('#first_name').val();  
           var lastName = $('#last_name').val();  
           var extension = $('#user_image').val().split('.').pop().toLowerCase();  
           if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)  
           {  
                alert("Invalid Image File");  
                $('#user_image').val('');  
                return false;  
           }  
           if(firstName != '' && lastName != '')  
           {  
                $.ajax({  
                     url:"<?php echo base_url() . 'crud/user_action'?>",  
                     method:'POST',  
                     data:new FormData(this),  
                     contentType:false,  
                     processData:false,  
                     success:function(data)  
                     {  
                          alert(data);  
                          $('#user_form')[0].reset();  
                          $('#userModal').modal('hide');  
                          dataTable.ajax.reload();  
                     }  
                });  
           }  
           else  
           {  
                alert("Bother Fields are Required");  
           }  
      });  
 });  
 </script>  

Tuesday, 6 December 2016

DataTables - Server-side Processing in Codeigniter using Ajax



From this tutorial we have started learning one new topics in Codeigniter tutorial. In this topics we will discuss how can we make crud system by using Ajax with Codeigniter framework. In this system we will use DataTables Jquery plugin for display data in tabular format and we will also use Bootstrap modals for inserting and updating data. Here we will implement DataTables server side processing by using Ajax. This is the first part in which we will fetch data from Mysql table by using Ajax in Codeigniter Application and then after we will displaying that data in on web page by using DataTables jquery plugin with server side processing. In server side processing we have to write query for search, order and pagination at server side. This all things we will learn in this part. We have make simple query for all different condition like searching, ordering or even pagination and this query has been called by Ajax in codeigniter framework. So we can smoothly search table, can see data in different order or pagination which has been handle by Ajax server side processing in data tables. We can perform different operation in data table by using Ajax in Codeigniter application.




Source Code


Controllers - crud.php


 <?php  
 defined('BASEPATH') OR exit('No direct script access allowed');  
 class Crud extends CI_Controller {  
      //functions  
      function index(){  
           $data["title"] = "Codeigniter Ajax CRUD with Data Tables and Bootstrap Modals";  
           $this->load->view('crud_view', $data);  
      }  
      function fetch_user(){  
           $this->load->model("crud_model");  
           $fetch_data = $this->crud_model->make_datatables();  
           $data = array();  
           foreach($fetch_data as $row)  
           {  
                $sub_array = array();  
                $sub_array[] = '<img src="'.base_url().'upload/'.$row->image.'" class="img-thumbnail" width="50" height="35" />';  
                $sub_array[] = $row->first_name;  
                $sub_array[] = $row->last_name;  
                $sub_array[] = '<button type="button" name="update" id="'.$row->id.'" class="btn btn-warning btn-xs">Update</button>';  
                $sub_array[] = '<button type="button" name="delete" id="'.$row->id.'" class="btn btn-danger btn-xs">Delete</button>';  
                $data[] = $sub_array;  
           }  
           $output = array(  
                "draw"                    =>     intval($_POST["draw"]),  
                "recordsTotal"          =>      $this->crud_model->get_all_data(),  
                "recordsFiltered"     =>     $this->crud_model->get_filtered_data(),  
                "data"                    =>     $data  
           );  
           echo json_encode($output);  
      }  
 }  

Models - crud_model.php


 <?php  
 class Crud_model extends CI_Model  
 {  
      var $table = "users";  
      var $select_column = array("id", "first_name", "last_name", "image");  
      var $order_column = array(null, "first_name", "last_name", null, null);  
      function make_query()  
      {  
           $this->db->select($this->select_column);  
           $this->db->from($this->table);  
           if(isset($_POST["search"]["value"]))  
           {  
                $this->db->like("first_name", $_POST["search"]["value"]);  
                $this->db->or_like("last_name", $_POST["search"]["value"]);  
           }  
           if(isset($_POST["order"]))  
           {  
                $this->db->order_by($this->order_column[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);  
           }  
           else  
           {  
                $this->db->order_by('id', 'DESC');  
           }  
      }  
      function make_datatables(){  
           $this->make_query();  
           if($_POST["length"] != -1)  
           {  
                $this->db->limit($_POST['length'], $_POST['start']);  
           }  
           $query = $this->db->get();  
           return $query->result();  
      }  
      function get_filtered_data(){  
           $this->make_query();  
           $query = $this->db->get();  
           return $query->num_rows();  
      }       
      function get_all_data()  
      {  
           $this->db->select("*");  
           $this->db->from($this->table);  
           return $this->db->count_all_results();  
      }  
 }  

Views - crud_view.php


 <html>  
 <head>  
   <title><?php echo $title; ?></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://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>  
      <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>            
      <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />  
   <style>  
           body  
           {  
                margin:0;  
                padding:0;  
                background-color:#f1f1f1;  
           }  
           .box  
           {  
                width:900px;  
                padding:20px;  
                background-color:#fff;  
                border:1px solid #ccc;  
                border-radius:5px;  
                margin-top:10px;  
           }  
      </style>  
 </head>  
 <body>  
      <div class="container box">  
           <h3 align="center"><?php echo $title; ?></h3><br />  
           <div class="table-responsive">  
                <br />  
                <table id="user_data" class="table table-bordered table-striped">  
                     <thead>  
                          <tr>  
                               <th width="10%">Image</th>  
                               <th width="35%">First Name</th>  
                               <th width="35%">Last Name</th>  
                               <th width="10%">Edit</th>  
                               <th width="10%">Delete</th>  
                          </tr>  
                     </thead>  
                </table>  
           </div>  
      </div>  
 </body>  
 </html>  
 <script type="text/javascript" language="javascript" >  
 $(document).ready(function(){  
      var dataTable = $('#user_data').DataTable({  
           "processing":true,  
           "serverSide":true,  
           "order":[],  
           "ajax":{  
                url:"<?php echo base_url() . 'crud/fetch_user'; ?>",  
                type:"POST"  
           },  
           "columnDefs":[  
                {  
                     "targets":[0, 3, 4],  
                     "orderable":false,  
                },  
           ],  
      });  
 });  
 </script>  

Friday, 2 December 2016

PHPExcel - Export Excel file into Mysql Database using Ajax



In this post we are going to learn how to export excel file and insert that excel file data into mysql data by using PHP with Ajax. In this example we will export excel file data into mysql database without page refresh this is because we have use ajax request with jquery for upload excel file in php script. For fetch data from excel file we have use PHPExcel library, by using this PHPExcel library we can fetch data from excel and we can use that data into php script. PHPExcel library is used for read, write or create excel file in php script. If you want to fetch data from any excel document to php then you can use this PHPExcel library. We have use ajax request to upload upload excel file and then after by using this PHPExcel library we have use that excel data in php script. So we have make simple data export system, in this system you can export excel data into mysql database without page refresh. This is because we have use ajax method for upload excel file to sever. For exporting excel data we have use PHPExcel library. By using this library we can smoothly export large amount of excel data to database. This system is very important if you are working on any enterprise level application. In that application you have large amount of data in excel file and you want to export that to mysql database server. Then at that time this type of system is very important. In this we have use ajax method so it will export data to server without page refresh. That means it will export data to server fast as compare to simple php script.

You can download PHPExcel class from this link - https://phpexcel.codeplex.com/releases/view/119187



Souce Code


index.php


 <html>  
      <head>  
           <title>PHPExcel - Export Excel file into Mysql Database using Ajax</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>  
           <style>  
                body  
                {  
                     margin:0;  
                     padding:0;  
                     background-color:#f1f1f1;  
                }  
                .box  
                {  
                     width:900px;  
                     padding:20px;  
                     background-color:#fff;  
                     border:1px solid #ccc;  
                     border-radius:5px;  
                     margin-top:100px;  
                }  
           </style>  
      </head>  
      <body>  
           <div class="container box">  
                <h3 align="center">PHPExcel - Export Excel file into Mysql Database using Ajax</h3>  
                <br /><br />  
                <br /><br />  
                <form mehtod="post" id="export_excel">  
                     <label>Select Excel</label>  
                     <input type="file" name="excel_file" id="excel_file" />  
                </form>  
                <br />  
                <br />  
                <div id="result">  
                </div>  
           </div>  
      </body>  
 </html>  
 <script>  
 $(document).ready(function(){  
      $('#excel_file').change(function(){  
           $('#export_excel').submit();  
      });  
      $('#export_excel').on('submit', function(event){  
           event.preventDefault();  
           $.ajax({  
                url:"export.php",  
                method:"POST",  
                data:new FormData(this),  
                contentType:false,  
                processData:false,  
                success:function(data){  
                     $('#result').html(data);  
                     $('#excel_file').val('');  
                }  
           });  
      });  
 });  
 </script>  

export.php


 <?php  
 //export.php  
 if(!empty($_FILES["excel_file"]))  
 {  
      $connect = mysqli_connect("localhost", "root", "", "testing");  
      $file_array = explode(".", $_FILES["excel_file"]["name"]);  
      if($file_array[1] == "xls")  
      {  
           include("PHPExcel/IOFactory.php");  
           $output = '';  
           $output .= "  
           <label class='text-success'>Data Inserted</label>  
                <table class='table table-bordered'>  
                     <tr>  
                          <th>Customer Name</th>  
                          <th>Address</th>  
                          <th>City</th>  
                          <th>Postal Code</th>  
                          <th>Country</th>  
                     </tr>  
                     ";  
           $object = PHPExcel_IOFactory::load($_FILES["excel_file"]["tmp_name"]);  
           foreach($object->getWorksheetIterator() as $worksheet)  
           {  
                $highestRow = $worksheet->getHighestRow();  
                for($row=2; $row<=$highestRow; $row++)  
                {  
                     $name = mysqli_real_escape_string($connect, $worksheet->getCellByColumnAndRow(1, $row)->getValue());  
                     $address = mysqli_real_escape_string($connect, $worksheet->getCellByColumnAndRow(2, $row)->getValue());  
                     $city = mysqli_real_escape_string($connect, $worksheet->getCellByColumnAndRow(3, $row)->getValue());  
                     $postal_code = mysqli_real_escape_string($connect, $worksheet->getCellByColumnAndRow(4, $row)->getValue());  
                     $country = mysqli_real_escape_string($connect, $worksheet->getCellByColumnAndRow(5, $row)->getValue());  
                     $query = "  
                     INSERT INTO tbl_customer  
                     (CustomerName, Address, City, PostalCode, Country)   
                     VALUES ('".$name."', '".$address."', '".$city."', '".$postal_code."', '".$country."')  
                     ";  
                     mysqli_query($connect, $query);  
                     $output .= '  
                     <tr>  
                          <td>'.$name.'</td>  
                          <td>'.$address.'</td>  
                          <td>'.$city.'</td>  
                          <td>'.$postal_code.'</td>  
                          <td>'.$country.'</td>  
                     </tr>  
                     ';  
                }  
           }  
           $output .= '</table>';  
           echo $output;  
      }  
      else  
      {  
           echo '<label class="text-danger">Invalid File</label>';  
      }  
 }  
 ?>  

tbl_customer


 --  
 -- Table structure for table `tbl_customer`  
 --  
 CREATE TABLE IF NOT EXISTS `tbl_customer` (  
  `CustomerID` int(11) NOT NULL AUTO_INCREMENT,  
  `CustomerName` varchar(250) NOT NULL,  
  `Address` text NOT NULL,  
  `City` varchar(250) NOT NULL,  
  `PostalCode` varchar(30) NOT NULL,  
  `Country` varchar(100) NOT NULL,  
  PRIMARY KEY (`CustomerID`)  
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;  

Wednesday, 30 November 2016

PHP Ajax Crud - Insert Update Delete with Stored Procedure

Part 1 - Select or Fetch Data by using Stored Procedure in PHP with Ajax JQuery 


Part 2 - Insert or Add Data by using Stored Procedure in PHP with Ajax JQuery


Part 3 - Update or Edit Data by using Stored Procedure in PHP with Ajax JQuery


Part 4 - Delete or Remove Data by using Stored Procedure in PHP with Ajax JQuery



If you are looking for tutorial on Stored Procedure for Crud operation in PHP with Ajax Jquery then we are going to discuss one more advance topic in web development. In this tutorial we will discuss how can we use store procedure with Ajax and Jquery for Insert Update Delete and fetch data from Mysql table in php script. In this tutorial we will make crud operation in php with ajax. For making crud operation we will use stored procedure for making crud operation in php with Ajax. In this crud operation we have use Ajax with php so all operation will be done without page refresh. Here crud means create, read, update and delete of database table data. Insert, Update, and Delete features is almost use in every website in PHP with Ajax. In this script, we will fetch users data from database and display that user data on web page with update link and delete link. By this type of link we can update and delete data from database. This operation has been done without page refresh event. For this type of operation here we will use stored procedure. First of all what is stored procedure. Stored procedure is a collection of query. It is also called pre compiled sql query. Stored Procedure is mainly used for enterprise level application. If you are working on any large data project then you can use stored procedure for Insert Update Delete of data operation. So here we will stored procedure from crud operation in php with Ajax.

This is our complete system in which we can fetch, insert, edit and delete data from database by using stored procedure in php script with Ajax request. Insert, Fetch, Update and delete records from database by using php is a very simple feature for new programmer. But here is something complex task, In this task first of all we have use stored procedure for crud operation and second is we have use ajax method with stored procedure for crud operation. So it is something new feature, if you have working on very large data application then you can use stored procedure and with Ajax request. You application working speed will be increase than normal php application. This is because stored procedure execute query at database server not on php script. So your application will execute faster than normal php application. Insert Update delete and fetch data is the normal operation in any web application. So if this operation perform fast then your application will run fast. So for execute this basic operation fast, then you can use stored procedure in your application. Mainly stored procedure are stored in your data base and it will execute from database so it will reduce execution load on your php page. So this way we can increase execution speed of any web application by using stored procedure in php script with Ajax method.

Source Code


Users


 --  
 -- Database: `crud`  
 --  
 CREATE DATABASE `crud` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;  
 USE `crud`;  
 -- --------------------------------------------------------  
 --  
 -- Table structure for table `users`  
 --  
 CREATE TABLE IF NOT EXISTS `users` (  
  `id` int(11) NOT NULL AUTO_INCREMENT,  
  `first_name` varchar(150) NOT NULL,  
  `last_name` varchar(150) NOT NULL,  
  PRIMARY KEY (`id`)  
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=23 ;  
 --  
 -- Dumping data for table `users`  
 --  
 INSERT INTO `users` (`id`, `first_name`, `last_name`) VALUES  
 (17, 'Rosie', 'Peele'),  
 (18, 'Joseph', 'Harman'),  
 (19, 'John', 'Moss'),  
 (20, 'Lillie', 'Ferrari'),  
 (21, 'Yolanda', 'Green'),  
 (22, 'Cara', 'Gariepy');  

index.php


 <html>  
      <head>  
           <title>PHP Ajax Crud - Insert Update Delete with Stored Procedure</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>  
           <style>  
                body  
                {  
                     margin:0;  
                     padding:0;  
                     background-color:#f1f1f1;  
                }  
                .box  
                {  
                     width:750px;  
                     padding:20px;  
                     background-color:#fff;  
                     border:1px solid #ccc;  
                     border-radius:5px;  
                     margin-top:100px;  
                }  
           </style>  
      </head>  
      <body>  
           <div class="container box">  
                <h3 align="center">PHP Ajax Crud - Insert Update Delete with Stored Procedure</h3>  
                <br /><br />  
                <br /><br />  
                <label>Enter First Name</label>  
                <input type="text" name="first_name" id="first_name" class="form-control" />  
                <br />  
                <label>Enter Last Name</label>  
                <input type="text" name="last_name" id="last_name" class="form-control" />  
                <br /><br />  
                <div align="center">  
                     <input type="hidden" name="id" id="user_id" />  
                     <button type="button" name="action" id="action" class="btn btn-warning">Add</button>  
                </div>  
                <br />  
                <br />  
                <div id="result" class="table-responsive">  
                </div>  
           </div>  
      </body>  
 </html>  
 <script>  
 $(document).ready(function(){  
      fetchUser();  
      function fetchUser()  
      {  
           var action = "select";  
           $.ajax({  
                url : "select.php",  
                method:"POST",  
                data:{action:action},  
                success:function(data){  
                     $('#first_name').val('');  
                     $('#last_name').val('');  
                     $('#action').text("Add");  
                     $('#result').html(data);  
                }  
           });  
      }  
      $('#action').click(function(){  
           var firstName = $('#first_name').val();  
           var lastName = $('#last_name').val();  
           var id = $('#user_id').val();  
           var action = $('#action').text();  
           if(firstName != '' && lastName != '')  
           {  
                $.ajax({  
                     url : "action.php",  
                     method:"POST",  
                     data:{firstName:firstName, lastName:lastName, id:id, action:action},  
                     success:function(data){  
                          alert(data);  
                          fetchUser();  
                     }  
                });  
           }  
           else  
           {  
                alert("Both Fields are Required");  
           }  
      });  
      $(document).on('click', '.update', function(){  
           var id = $(this).attr("id");  
           $.ajax({  
                url:"fetch.php",  
                method:"POST",  
                data:{id:id},  
                dataType:"json",  
                success:function(data){  
                     $('#action').text("Edit");  
                     $('#user_id').val(id);  
                     $('#first_name').val(data.first_name);  
                     $('#last_name').val(data.last_name);  
                }  
           })  
      });  
      $(document).on('click', '.delete', function(){  
           var id = $(this).attr("id");  
           if(confirm("Are you sure you want to remove this data?"))  
           {  
                var action = "Delete";  
                $.ajax({  
                     url:"action.php",  
                     method:"POST",  
                     data:{id:id, action:action},  
                     success:function(data)  
                     {  
                          fetchUser();  
                          alert(data);  
                     }  
                })  
           }  
           else  
           {  
                return false;  
           }  
      });  
 });  
 </script>  

select.php


 <?php  
 //select.php  
 $output = '';  
 $connect = mysqli_connect("localhost", "root", "", "crud");  
 if(isset($_POST["action"]))  
 {  
      $procedure = "  
      CREATE PROCEDURE selectUser()  
      BEGIN  
      SELECT * FROM users ORDER BY id DESC;  
      END;  
      ";  
      if(mysqli_query($connect, "DROP PROCEDURE IF EXISTS selectUser"))  
      {  
           if(mysqli_query($connect, $procedure))  
           {  
                $query = "CALL selectUser()";  
                $result = mysqli_query($connect, $query);  
                $output .= '  
                     <table class="table table-bordered">  
                          <tr>  
                               <th width="35%">First Name</th>  
                               <th width="35%">Last Name</th>  
                               <th width="15%">Update</th>  
                               <th width="15%">Delete</th>  
                          </tr>  
                ';  
                if(mysqli_num_rows($result) > 0)  
                {  
                     while($row = mysqli_fetch_array($result))  
                     {  
                          $output .= '  
                               <tr>  
                                    <td>'.$row["first_name"].'</td>  
                                    <td>'.$row["last_name"].'</td>  
                                    <td><button type="button" name="update" id="'.$row["id"].'" class="update btn btn-success btn-xs">Update</button></td>  
                                    <td><button type="button" name="delete" id="'.$row["id"].'" class="delete btn btn-danger btn-xs">Delete</button></td>  
                               </tr>  
                          ';  
                     }  
                }  
                else  
                {  
                     $output .= '  
                          <tr>  
                               <td colspan="4">Data not Found</td>  
                          </tr>  
                     ';  
                }  
                $output .= '</table>';  
                echo $output;  
           }  
      }  
 }  
 ?>  

action.php


 <?php  
 //action.php  
 if(isset($_POST["action"]))  
 {  
      $output = '';  
      $connect = mysqli_connect("localhost", "root", "", "crud");  
      if($_POST["action"] =="Add")  
      {  
           $first_name = mysqli_real_escape_string($connect, $_POST["firstName"]);  
           $last_name = mysqli_real_escape_string($connect, $_POST["lastName"]);  
           $procedure = "  
                CREATE PROCEDURE insertUser(IN firstName varchar(250), lastName varchar(250))  
                BEGIN  
                INSERT INTO users(first_name, last_name) VALUES (firstName, lastName);   
                END;  
           ";  
           if(mysqli_query($connect, "DROP PROCEDURE IF EXISTS insertUser"))  
           {  
                if(mysqli_query($connect, $procedure))  
                {  
                     $query = "CALL insertUser('".$first_name."', '".$last_name."')";  
                     mysqli_query($connect, $query);  
                     echo 'Data Inserted';  
                }  
           }  
      }  
      if($_POST["action"] == "Edit")  
      {  
           $first_name = mysqli_real_escape_string($connect, $_POST["firstName"]);  
           $last_name = mysqli_real_escape_string($connect, $_POST["lastName"]);  
           $procedure = "  
                CREATE PROCEDURE updateUser(IN user_id int(11), firstName varchar(250), lastName varchar(250))  
                BEGIN   
                UPDATE users SET first_name = firstName, last_name = lastName  
                WHERE id = user_id;  
                END;   
           ";  
           if(mysqli_query($connect, "DROP PROCEDURE IF EXISTS updateUser"))  
           {  
                if(mysqli_query($connect, $procedure))  
                {  
                     $query = "CALL updateUser('".$_POST["id"]."', '".$first_name."', '".$last_name."')";  
                     mysqli_query($connect, $query);  
                     echo 'Data Updated';  
                }  
           }  
      }  
      if($_POST["action"] == "Delete")  
      {  
           $procedure = "  
           CREATE PROCEDURE deleteUser(IN user_id int(11))  
           BEGIN   
           DELETE FROM users WHERE id = user_id;  
           END;  
           ";  
           if(mysqli_query($connect, "DROP PROCEDURE IF EXISTS deleteUser"))  
           {  
                if(mysqli_query($connect, $procedure))  
                {  
                     $query = "CALL deleteUser('".$_POST["id"]."')";  
                     mysqli_query($connect, $query);  
                     echo 'Data Deleted';  
                }  
           }  
      }  
 }  
 ?>  

fetch.php


 <?php  
 //fetch.php  
 $connect = mysqli_connect("localhost","root", "", "crud");  
 if(isset($_POST["id"]))  
 {  
      $output = array();  
      $procedure = "  
      CREATE PROCEDURE whereUser(IN user_id int(11))  
      BEGIN   
      SELECT * FROM users WHERE id = user_id;  
      END;   
      ";  
      if(mysqli_query($connect, "DROP PROCEDURE IF EXISTS whereUser"))  
      {  
           if(mysqli_query($connect, $procedure))  
           {  
                $query = "CALL whereUser(".$_POST["id"].")";  
                $result = mysqli_query($connect, $query);  
                while($row = mysqli_fetch_array($result))  
                {  
                     $output['first_name'] = $row["first_name"];  
                     $output['last_name'] = $row["last_name"];  
                }  
                echo json_encode($output);  
           }  
      }  
 }  
 ?>  

Friday, 25 November 2016

Upload Multiple Images by Using PHP Ajax Jquery with Bootstrap Modal



This one more tutorial on how to use Bootstrap Modal in Web Development. In this post we will use Bootstrap Modal for upload multiple images on folder by using PHP script with Ajax Jquery without refreshing of page. In this example we will make system for uploading one or more than one image to the specified path. Here we will use Bootstrap Modal for selecting multiple images. On web page we will put simple button and when we have click on that button then after modal will popup on web page and In modal we will put input type file tag and from that tag we can select multiple images for upload. For uploading images to specified path we have use php script for uploading multiple images to specified path as back end by called by Ajax request. For this things we have create one button and then after we have create modal. By clicking on button we can pop up modal on web page. From this modal we can select multiple file and when we have select file then at that time jquery code has been execute and form has been submitted. When form submitted after we have create ajax request and by using form data object we have send selected file data with ajax request to the php script and by php script we have upload multiple images to the folder. After uploading image we have fetch all images from folder by using glob() function and then after we have display images on web page.




Source Code


index.php


 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | Upload Multiple Image by Using PHP Ajax Jquery with Bootstrap Modal</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>  
           <br />  
           <div class="container">  
                <h3 align="center">Upload Multiple Image by Using PHP Ajax Jquery with Bootstrap Modal</h3><br />  
                <br />  
                <br />  
                <div align="center">  
                     <button type="button" data-toggle="modal" data-target="#uploadModal" class="btn btn-info btn-lg">Upload Images</button>  
                </div>  
                <br /><br />  
                <div id="gallery">  
                <?php  
                $images = glob("upload/*.*");  
                foreach($images as $image)  
                {  
                     echo '<div class="col-md-1" align="center" ><img src="' . $image .'" width="100px" height="100px" style="margin-top:15px; padding:8px; border:1px solid #ccc;" /></div>';  
                }  
                ?>  
                </div>  
                <br />  
                <br />  
           </div>  
           <br />  
      </body>  
 </html>  
 <div id="uploadModal" 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">Upload Multiple Files</h4>  
                </div>  
                <div class="modal-body">  
                     <form method="post" id="upload_form">  
                          <label>Select Multiple Image</label>  
                          <input type="file" name="images[]" id="select_image" multiple />  
                     </form>  
                </div>  
           </div>  
      </div>  
 </div>  
 <script>  
 $(document).ready(function(){  
      $('#select_image').change(function(){3  
           $('#upload_form').submit();  
      });  
      $('#upload_form').on('submit', function(e){  
           e.preventDefault();  
           $.ajax({  
                url :"upload.php",  
                method:"POST",  
                data:new FormData(this),  
                contentType:false,  
                processData:false,  
                success:function(data){  
                     $('#select_image').val('');  
                     $('#uploadModal').modal('hide');  
                     $('#gallery').html(data);  
                }  
           })  
      });  
 });  
 </script>  

upload.php


 <?php  
 //upload.php  
 $output = '';  
 if(is_array($_FILES))  
 {  
      foreach($_FILES['images']['name'] as $name => $value)  
      {  
           $file_name = explode(".", $_FILES['images']['name'][$name]);  
           $allowed_extension = array("jpg", "jpeg", "png", "gif");  
           if(in_array($file_name[1], $allowed_extension))  
           {  
                $new_name = rand() . '.'. $file_name[1];  
                $sourcePath = $_FILES["images"]["tmp_name"][$name];  
                $targetPath = "upload/".$new_name;  
                move_uploaded_file($sourcePath, $targetPath);  
           }  
      }  
      $images = glob("upload/*.*");  
      foreach($images as $image)  
      {  
           $output .= '<div class="col-md-1" align="center" ><img src="' . $image .'" width="100px" height="100px" style="margin-top:15px; padding:8px; border:1px solid #ccc;" /></div>';  
      }  
      echo $output;  
 }  
 ?>  

Thursday, 24 November 2016

Codeigniter Tutorial - Check Email availability using Ajax



This our one more tutorial in Codeigniter. In this tutorial we will discussing on how can we check email is available for registration or not by using Ajax with Jquery in Codeigniter framework. In most of the website registration we have use email for identify for login into system, then at that time we want to check particular email is already register into our system or not. So it is very important task to check email is already register or not at the time of registration. So In this video we have seen how can we validate email already registered or not in codeigniter application by using Ajax with Jquery. Here we have simple load register page from controller and then after on that view page we have write jquery code on textbox change event. So when we have enter email and go to password field then jquery code execute and in that code we have make ajax request and by using we have send request to controller and in controller first we have check email is proper or not if email is proper then it again check email is available in database or not so it go to model and in it will check email register or not and send result to controller and controller send result to view page. So This way whole cycle of codeigniter framework will run for checking email register or not by using Ajax with Jquery.




Source Code


Controller - main.php


 <?php  
 defined('BASEPATH') OR exit('No direct script access allowed');  
 class Main extends CI_Controller {  
      //functions  
      function email_availibility()  
      {  
           $data["title"] = "Codeigniter Tutorial - Check Email availibility using Ajax";  
           $this->load->view("email_availibility", $data);  
      }  
      function check_email_avalibility()  
      {  
           if(!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL))  
           {  
                echo '<label class="text-danger"><span class="glyphicon glyphicon-remove"></span> Invalid Email</span></label>';  
           }  
           else  
           {  
                $this->load->model("main_model");  
                if($this->main_model->is_email_available($_POST["email"]))  
                {  
                     echo '<label class="text-danger"><span class="glyphicon glyphicon-remove"></span> Email Already register</label>';  
                }  
                else  
                {  
                     echo '<label class="text-success"><span class="glyphicon glyphicon-ok"></span> Email Available</label>';  
                }  
           }  
      }       
 }  
 ?>  

Models - main_model.php


 <?php  
 class Main_model extends CI_Model  
 {  
      function is_email_available($email)  
      {  
           $this->db->where('email', $email);  
           $query = $this->db->get("register");  
           if($query->num_rows() > 0)  
           {  
                return true;  
           }  
           else  
           {  
                return false;  
           }  
      }  
 }  
 ?>  

Views - email_availibility.php


 <!DOCTYPE html>  
 <html>  
 <head>  
      <title>Webslesson | <?php echo $title; ?></title>  
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />  
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>  
 </head>  
 <body>  
      <div class="container" style="width:600px">  
           <br /><br /><br />  
           <h3><?php echo $title; ?></h3>  
           <br />  
           <label>Enter Email</label>  
           <input type="text" name="email" id="email" class="form-control" />  
           <span id="email_result"></span>  
           <br /><br />  
           <label>Enter Password</label>  
           <input type="text" name="password" id="password" class="form-control" />  
      </div>  
 </body>  
 </html>  
 <script>  
 $(document).ready(function(){  
      $('#email').change(function(){  
           var email = $('#email').val();  
           if(email != '')  
           {  
                $.ajax({  
                     url:"<?php echo base_url(); ?>main/check_email_avalibility",  
                     method:"POST",  
                     data:{email:email},  
                     success:function(data){  
                          $('#email_result').html(data);  
                     }  
                });  
           }  
      });  
 });  
 </script>  

Wednesday, 23 November 2016

Make accordion by using Bootstrap Collapse and Panels with PHP Script



If you want to make accordion by using large amount of dynamic data then in this post we are going to learn how to use Bootstrap Collapse with php script. By Bootstrap Collapse we will create accordion from dynamic data get from database and display on web page. By using Bootstrap Collapse we can display large amount of data on web page. We can hide content and only visible after we have click on that content. So by using Bootstrap Collapse we have create accordion and for see particular content by just click on title of that particular content. Here we will use display post title and post description and by using Bootstrap Collapse we will hide post description and only display post title. For seeing post description we have to click on post title then after we can see the post description of that post. So this way we can load large amount of content on single page by using Bootstrap Collapse. So this way we can load large amount of content on single web page in very less amount of space. In this post we have use bootstrap collapse and panels and by using both features we have make simple accordion. For making according first we have fetch data from table and then after we have print that data under panels and collapse class element. This way we have make accordion by using bootstrap collapse and panel class with php script.



Source Code


index.php


 <?php   
 $connect = mysqli_connect("localhost", "root", "", "testing");  
 $query = "SELECT * FROM tbl_posts ORDER BY post_title ASC";  
 $result = mysqli_query($connect, $query);  
 ?>  
 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | Make accordion by using Bootstrap Collapse and Panels with PHP Script</title>  
           <script src="jquery.js"></script>  
           <link rel="stylesheet" href="bootstrap.css" />  
           <script src="bootstrap.js"></script>  
      </head>  
      <body>  
           <br />  
           <div class="container" style="width:700px;">  
                <h3 align="center">Make accordion by using Bootstrap Collapse and Panels with PHP Script</h3><br />  
                <br />  
                <div class="panel-group" id="posts">  
                <?php  
                while($row = mysqli_fetch_array($result))  
                {  
                ?>  
                     <div class="panel panel-default">  
                          <div class="panel-heading">  
                               <h4 class="panel-title">  
                                    <a href="#<?php echo $row["post_id"]; ?>" data-toggle="collapse" data-parent="#posts"><?php echo $row["post_title"]; ?></a>  
                               </h4>  
                          </div>  
                          <div id="<?php echo $row["post_id"]; ?>" class="panel-collapse collapse">  
                               <div class="panel-body">  
                               <?php echo $row["post_desc"]; ?>  
                               </div>  
                          </div>  
                     </div>  
                <?php  
                }  
                ?>  
                </div>  
           </div>  
           <br />  
      </body>  
 </html>  

tbl_posts


 --  
 -- Table structure for table `tbl_posts`  
 --  
 CREATE TABLE IF NOT EXISTS `tbl_posts` (  
  `post_id` int(11) NOT NULL AUTO_INCREMENT,  
  `post_title` varchar(150) NOT NULL,  
  `post_desc` text NOT NULL,  
  PRIMARY KEY (`post_id`)  
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;