Tuesday 5 February 2019

Insert or Add Data using jQuery Dialogify with PHP Ajax


This is second post on jQuery Dialogify plugin with PHP. And in this post we will discuss how to use jQuery Dialogify Plugin for insert or add data into Mysql table using PHP with Ajax. In previous post we have seen how to load dynamic mysql data into pop up dialog box using jQuery Dialogify plugin with PHP Ajax. Inserting of Data is a basic function of any application. If you want to make single page CRUD application then you have to perform all CRUD option on same page without going to another page. For do all operation on Single page you have to make form for insert data in pop up modal dialog box.

For make pop up dialog box, In one of our tutorial in which we have use Bootstrap modal for use Insert data with PHP Ajax. By using Bootstrap modal we can make pop up modal dialog box. But now we want to use jQuery Dialogify plugin for make pop up dialog box, and in this modal dialog box we want to make insert data form. Here we will not only insert data into mysql table but also we will also upload image also with data insertion. So, here we have use jquery Dialogify plugin for insert data with upload file also using PHP with Ajax. So, with jQuery Dialogify plugin we cannot make form under pop up dialog box directly.

How to make Form in jQuery Dialogify Plugin


If we have use jQuery Dialogify Plugin for insert data then for insert data we have to make form for submit data to server. But in this plugin we cannot directly make form in pop up dialog box, but for make form, we have to define form fields in some other php file. In that file we have to just define form field, this plugin will automatically add form tag. Now the question arise how other php file form will be append into jQuery Dialogify pop up modal. For this we have to write new Dialogify() method, and under this method we have to define php file in which we have define form field. This method will pop up modal dialog box with form fields, which has been define php file. Below you can find complete source code of how to use jQuery Dialogify plugin for insert or add data into mysql using PHP with Ajax.



Insert or Add Data using jQuery Dialogify with PHP Ajax




Source Code


Database



--
-- Table structure for table `tbl_employee`
--

CREATE TABLE `tbl_employee` (
  `id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `address` text NOT NULL,
  `gender` varchar(10) NOT NULL,
  `designation` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `images` varchar(150) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_employee`
--

INSERT INTO `tbl_employee` (`id`, `name`, `address`, `gender`, `designation`, `age`, `images`) VALUES
(6, 'Barbra K. Hurley', '1241 Canis Heights Drive\r\nLos Angeles, CA 90017', 'Female', 'Service technician', 26, 'image_35.jpg'),
(7, 'Antonio J. Forbes', '403 Snyder Avenue\r\nCharlotte, NC 28208', 'Male', 'Faller', 28, 'image_36.jpg'),
(8, 'Charles D. Horst', '1636 Walnut Hill Drive\r\nCincinnati, OH 45202', 'Male', 'Financial investigator', 29, 'image_37.jpg'),
(174, 'Martha B. Tomlinson', '4005 Bird Spring Lane, Houston, TX 77002', 'Female', 'Systems programmer', 28, 'image_44.jpg'),
(162, 'Jarrod D. Jones', '3827 Bingamon Road, Garfield Heights, OH 44125', 'Male', 'Manpower development advisor', 24, 'image_3.jpg'),
(192, 'Flora Reed', '4000 Hamilton Drive Cambridge, MD 21613', 'Female', 'Machine offbearer', 27, 'image_41.jpg'),
(193, 'Donna Case', '4781 Apple Lane Peoria, IL 61602', 'Female', 'Machine operator', 26, 'image_15.jpg'),
(194, 'William Lewter', '168 Little Acres Lane Decatur, IL 62526', 'Male', 'Process engineer', 25, 'image_46.jpg'),
(195, 'Nathaniel Leger', '3200 Harley Brook Lane Meadville, PA 16335', 'Male', 'Nurse', 21, 'image_34.jpg'),
(183, 'Steve John', '108, Vile Parle, CL', 'Male', 'Software Engineer', 29, 'image_47.jpg'),
(186, 'Louis C. Charmis', '1462 Juniper Drive\r\nBreckenridge, MI 48612', 'Male', 'Mental health counselor', 30, ''),
(200, 'June Barnard', '4465 Woodland Terrace Folsom, CA 95630', 'Female', 'Fishing vessel operator', 24, '');

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

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


database_connection.php



<?php

//database_connection.php

$username = 'root';
$password = '';
$connect = new PDO( 'mysql:host=localhost;dbname=testing', $username, $password );

?>



<html>
 <head>
  <title>Insert or Add Data using jQuery Dialogify with PHP 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://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>
  <script src="https://www.jqueryscript.net/demo/Dialog-Modal-Dialogify/dist/dialogify.min.js"></script>
 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center">Insert or Add Data using jQuery Dialogify with PHP Ajax</h3>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <div class="row">
      <div class="col-md-6">
       <h3 class="panel-title">Employee Data</h3>
      </div>
      <div class="col-md-6" align="right">
       <button type="button" name="add_data" id="add_data" class="btn btn-success btn-xs">Add</button>
      </div>
     </div>
    </div>
    <div class="panel-body">
     <div class="table-responsive">
      <span id="form_response"></span>
      <table id="user_data" class="table table-bordered table-striped">
       <thead>
        <tr>
         <td>Name</td>
         <td>Gender</td>
         <td>Designation</td>
         <td>Age</td>
         <td>View</td>
        </tr>
       </thead>
      </table>
      
     </div>
    </div>
   </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:"fetch.php",
   type:"POST"
  },
  "columnDefs":[
   {
    "targets":[4],
    "orderable":false,
   },
  ],

 });

 $(document).on('click', '.view', function(){
  var id = $(this).attr('id');
  var options = {
   ajaxPrefix: '',
   ajaxData: {id:id},
   ajaxComplete:function(){
    this.buttons([{
     type: Dialogify.BUTTON_PRIMARY
    }]);
   }
  };
  new Dialogify('fetch_single.php', options)
   .title('View Employee Details')
   .showModal();
 });
 
 $('#add_data').click(function(){
  var options = {
   ajaxPrefix:''
  };
  new Dialogify('add_data_form.php', options)
   .title('Add New Employee Data')
   .buttons([
    {
     text:'Cancle',
     click:function(e){
      this.close();
     }
    },
    {
     text:'Insert',
     type:Dialogify.BUTTON_PRIMARY,
     click:function(e)
     {
      var image_data = $('#images').prop("files")[0];
      var form_data = new FormData();
      form_data.append('images', image_data);
      form_data.append('name', $('#name').val());
      form_data.append('address', $('#address').val());
      form_data.append('gender', $('#gender').val());
      form_data.append('designation', $('#designation').val());
      form_data.append('age', $('#age').val());
      $.ajax({
       method:"POST",
       url:'insert_data.php',
       data:form_data,
       dataType:'json',
       contentType:false,
       cache:false,
       processData:false,
       success:function(data)
       {
        if(data.error != '')
        {
         $('#form_response').html('<div class="alert alert-danger">'+data.error+'</div>');
        }
        else
        {
         $('#form_response').html('<div class="alert alert-success">'+data.success+'</div>');
         dataTable.ajax.reload();
        }
       }
      });
     }
    }
   ]).showModal();
 });
 
 
});
</script>


fetch.php



<?php

//fetch.php

include('database_connection.php');
$query = '';
$output = array();
$query .= "SELECT * FROM tbl_employee ";
if(isset($_POST["search"]["value"]))
{
 $query .= 'WHERE name LIKE "%'.$_POST["search"]["value"].'%" OR address LIKE "%'.$_POST["search"]["value"].'%" OR gender LIKE "%'.$_POST["search"]["value"].'%" OR designation LIKE "%'.$_POST["search"]["value"].'%" OR age LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["order"]))
{
 $query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
 $query .= 'ORDER BY id DESC ';
}
if($_POST["length"] != -1)
{
 $query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
 $sub_array = array();
 $sub_array[] = $row["name"];
 $sub_array[] = $row["gender"];
 $sub_array[] = $row["designation"];
 $sub_array[] = $row["age"];
 $sub_array[] = '<button type="button" name="view" id="'.$row["id"].'" class="btn btn-primary btn-xs view">View</button>';
 $data[] = $sub_array;
}

function get_total_all_records($connect)
{
 $statement = $connect->prepare("SELECT * FROM tbl_employee");
 $statement->execute();
 $result = $statement->fetchAll();
 return $statement->rowCount();
}

$output = array(
 "draw"    => intval($_POST["draw"]),
 "recordsTotal"  =>  $filtered_rows,
 "recordsFiltered" => get_total_all_records($connect),
 "data"    => $data
);
echo json_encode($output);
?>


fetch_single.php



<?php

//fetch_single.php

include('database_connection.php');

if(isset($_GET["id"]))
{
 $query = "SELECT * FROM tbl_employee WHERE id = '".$_GET["id"]."'";

 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $output = '<div class="row">';
 foreach($result as $row)
 {
  $images = '';
  if($row["images"] != '')
  {
   $images = '<img src="images/'.$row["images"].'" class="img-responsive img-thumbnail" />';
  }
  else
  {
   $images = '<img src="https://www.gravatar.com/avatar/38ed5967302ec60ff4417826c24feef6?s=80&d=mm&r=g" class="img-responsive img-thumbnail" />';
  }
  $output .= '
  <div class="col-md-3">
   <br />
   '.$images.'
  </div>
  <div class="col-md-9">
   <br />
   <p><label>Name :&nbsp;</label>'.$row["name"].'</p>
   <p><label>Address :&nbsp;</label>'.$row["address"].'</p>
   <p><label>Gender :&nbsp;</label>'.$row["gender"].'</p>
   <p><label>Designation :&nbsp;</label>'.$row["designation"].'</p>
   <p><label>Age :&nbsp;</label>'.$row["age"].' years</p>
  </div>
  </div><br />
  ';
 }
 echo $output;
}

?>







add_data_form.php



<div class="form-group">
 <label>Enter Employee Name</label>
 <input type="text" name="name" id="name" class="form-control" />
</div>
<div class="form-group">
 <label>Enter Employee Address</label>
 <textarea name="address" id="address" class="form-control"></textarea>
</div>
<div class="form-group">
 <label>Enter Employee Gender</label>
 <select name="gender" id="gender" class="form-control">
  <option value="Male">Male</option>
  <option value="Female">Female</option>
 </select>
</div>
<div class="form-group">
 <label>Enter Employee Desingation</label>
 <input type="text" name="designation" id="designation" class="form-control" />
</div>
<div class="form-group">
 <label>Enter Employee Age</label>
 <input type="text" name="age" id="age" class="form-control" />
</div>
<div class="form-group">
 <label>Select Employee Image</label>
 <input type="file" name="images" id="images" />
</div>


insert_data.php



<?php

//insert_data.php

include('database_connection.php');

if(isset($_POST["name"]))
{
 $error = '';
 $success = '';
 $name = '';
 $address = '';
 $designation = '';
 $age = '';
 $images = '';
 $gender = $_POST["gender"];
 if(empty($_POST["name"]))
 {
  $error .= '<p>Name is Required</p>';
 }
 else
 {
  $name = $_POST["name"];
 }
 if(empty($_POST["address"]))
 {
  $error .= '<p>Address is Required</p>';
 }
 else
 {
  $address = $_POST["address"];
 }
 if(empty($_POST["designation"]))
 {
  $error .= '<p>Designation is Required</p>';
 }
 else
 {
  $designation = $_POST["designation"];
 }
 if(empty($_POST["age"]))
 {
  $error .= '<p>Age is Required</p>';
 }
 else
 {
  $age = $_POST["age"];
 }

 if(isset($_FILES["images"]["name"]) && $_FILES["images"]["name"] != '')
 {
  $image_name = $_FILES["images"]["name"];
  $array = explode(".", $image_name);
  $extension = end($array);
  $temporary_name = $_FILES["images"]["tmp_name"];
  $allowed_extension = array("jpg","png");
  if(!in_array($extension, $allowed_extension))
  {
   $error .= '<p>Invalid Image</p>';
  }
  else
  {
   $images = rand() . '.' . $extension;
   move_uploaded_file($temporary_name, 'images/' . $images);
  }
 }
 if($error == '')
 {
  $data = array(
   ':name'   => $name,
   ':address'  => $address,
   ':gender'  => $gender,
   ':designation' => $designation,
   ':age'   => $age,
   ':images'  => $images
  );

  $query = "
  INSERT INTO tbl_employee 
  (name, address, gender, designation, age, images) 
  VALUES (:name, :address, :gender, :designation, :age, :images)
  ";
  $statement = $connect->prepare($query);
  $statement->execute($data);
  $success = 'Employee Data Inserted';
 }
 $output = array(
  'success'  => $success,
  'error'   => $error
 );
 echo json_encode($output);
}

?>


This is combine source code of View Dyanmic Data using Dialogify plugin post and Insert Data using Dialogify with PHP Ajax. If you have any query regarding this post, you can send your query via comment.

12 comments:

  1. BEARSTREET Trading Floor are some guidelines for picking the best day trading stocks and you will get all answer of how to pick stock for day trading and find Best 5 intraday trading strategies for selecting stocks without using chart. Contact us for any queries related to our products and services – 9999715635.

    ReplyDelete
  2. BEARSTREET intraday trading refers to the squaring off (buying and selling) the position on the same day. BEARSTREET Trading Floor on intraday trading tips page, Religare Online provides best intraday recommendations in stocks, commodities, currency and derivatives market. While day trading may lead to profits. Contact us for any queries related to our products and services – 9999715635.

    ReplyDelete
  3. The BEARSTREET intraday trading tools can be of great help to traders who are looking to make quick profits from day to day. BEARSTREET Trading Floor Intraday Stock cash tips help traders square off their positions within a day and usually avoid having over-night risks. Contact us for any queries related to our products and services – 9999715635.

    ReplyDelete
  4. If you want to learn how to make money daily in the stock market. So join BEARSTREET Trading Floor. We gives you a some unique share market trading techniques like research current trends, select a correct trading website and Practice trading before you put real money in. Contact us for any queries related to our products and services – 9999715635.

    ReplyDelete
  5. Learn from BEARSTREET Trading Floor the Best Day Trading Strategies for Beginner Traders. We provide trading services like Trade for own, Proprietary Day Trader and Trader Exchange Program. Yet day trading is not all that complicated once you learn a simple, rules-based strategy for anticipating market moves, such as that taught at BEARSTREET. Contact us for any queries related to our products and services – 9999715635.

    ReplyDelete
  6. Bearstreet Trading Floor is a very good training program. We gives you an insight of the share market. We teach us simple ways to analyze the stocks & select the stocks properly by implementing technical and fundamental analysis. Contact us for any queries related to our products and services – 9999715635.

    ReplyDelete
  7. We, at Bearstreet Trading Floor, provides intraday tips/recommendation to our customers for stock market. These tips are derived after careful and meticulous effort of our Research Analysts. Our intraday tips are given for best BSE stocks for intraday trading. Contact us for any queries related to our products and services – 9999715635.

    ReplyDelete
  8. Bearstreet Trading Floor is the top guiding to online day trading. Beginners who are learning how to day trade should read our trading services like Trade for own, Proprietary Day Trader and Trader Exchange Program. We have Experienced intraday traders who can get explore more advanced topics and how to make a living on the financial markets. Contact us for any queries related to our products and services – 9999715635.

    ReplyDelete
  9. Bearstreet Trading Floor is a leading financial services provider with presence in Indian and other global capital markets. Our main focus is on consistently developing and delivering high quality and high precision financial services to you which leads to create various opportunities of earnings. Contact us for any queries related to our products and services – 9999715635.

    ReplyDelete
  10. Top advices on Indian stock market, Intraday trading market and also get expert views, latest company results, top gainers/losers and more stock information at Bearstreet Trading Floor. So here are some guidelines for picking the top Intraday trading stocks. Contact us for any queries related to our products and services – 9999715635.

    ReplyDelete
  11. Day trading tips and tricks from beginners to day trading experts. Bearstreet Trading Floor tips will help traders of all experience levels develop more effective strategies for their portfolios. Our professional traders that you teach every new and experienced trader in our day trading floor. Contact us for any queries related to our products and services – 9999715635.

    ReplyDelete
  12. The image does not work, when I look at the data type of the image in the DB it is of type varchar(150).

    ReplyDelete