Thursday, 29 December 2016

PHP Mysql Ajax Crud using OOPS - Pagination


In the web project, pagination is the most essential element in which we can displayed large number of data from Mysql database to on webpage. Then in that time Pagination make by Ajax is a very Ajax pagination is a excellent idea because it will assist to increase visibility of your website User Interface. This tutorial will help you about how can you create the Ajax pagination in PHP Object Oriented programming Script using jQuery and MySQL. Here We have made the very simple but very powerful code to developed pagination with jQuery, Ajax, PHP, and MySQL.

By using Object Oriented PHP Script, We have first load data from the MySQL database with the Ajax pagination links. By Click on this Ajax pagination links, you can fetch the database table records except the records which you want to displayed. jQuery and Ajax will assist to fetch the data from the mysql database based on pagination links without refreshing of the page.

First We have make changes in load_data() function, in this function we have add first one argument like page.

function load_data(page)

After this in that function we have add that page argument data has been passed in Ajax data option to send the value of this page variable to action.php page.

data:{action:action, page:page},

Write JQuery code on click on pagination links. Here .pagination_link is the class name of Ajax Pagination Link. When click on pagination link this code will execute and it will fetch value from id attribute of particular pagination link. In an id attribute we have store page number. After fetching page number we have called load_data(page) function and in that function we have pass value of page variable and that function load data for that page.

              $(document).on('click', '.pagination_link', function(){
   var page = $(this).attr("id");
   load_data(page);
  });

This code write on action.php page under load data if condition. Here first $record_per_page = 5; That means we have set display five records on web page. Then after we have define $page variable. In this variable store the value of $_POST["page"] variable which is comes from ajax method. If it not received $_POST["page] variable then we have set $page variable value to 1.

                $record_per_page = 5;
  $page = '';

  if(isset($_POST["page"]))
  {
   $page = $_POST["page"];
  }
  else
  {
   $page = 1;
  }

After this we have calculate from where we have start fetching data from database.

$start_from = ($page - 1) * $record_per_page;

After this we have called get_data_in_table() function which we have made under crud class, this function will execute query and display result in table format

echo $object->get_data_in_table("SELECT * FROM users ORDER BY id DESC LIMIT $start_from, $record_per_page");

Make one function with name like make_pagination_link() in crud class, this function has generate pagination link and send pagination link.

        function make_pagination_link($query, $record_per_page)
 {
  $output = '';
  $result = $this->execute_query($query);
  $total_records = mysqli_num_rows($result);
  $total_pages = ceil($total_records/$record_per_page);
  for($i=1; $i<=$total_pages; $i++)
  {
   $output .= '<span class="pagination_link" style="cursor:pointer; padding:6px; border:1px solid #ccc;" id="'.$i.'">'.$i.'</span>';
  }
  return $output;
 }

Again go to action.php and called make_pagination_link() which return pagination link html format and which we have send to index page.

echo $object->make_pagination_link("SELECT * FROM users ORDER by id", $record_per_page);

Conclusion

So Pagination is the last part of our Crud system which is developed by Object Oriented PHP programming with Ajax JQuery method. Lastly Pagination is a very important features of any website, specially if you have many large number of data stored into your database and at that time you want to group that data into different part and display in different pages then at that time Ajax Pagination is done best job like, you can access different pages of data without going to next page but stay on single page. So it is very import for any web application.





Source Code of Whole System with Insert, Update Delete, Searching and Pagination


crud.php


<?php
class Crud
{
 //crud class
 public $connect;
 private $host = "localhost";
 private $username = 'root';
 private $password = '';
 private $database = 'crud';

 function __construct()
 {
  $this->database_connect();
 }

 public function database_connect()
 {
  $this->connect = mysqli_connect($this->host, $this->username, $this->password, $this->database);
 }

 public function execute_query($query)
 {
  return mysqli_query($this->connect, $query);
 }

 public function get_data_in_table($query)
 {
  $output = '';
  $result = $this->execute_query($query);
  $output .= '
  <table class="table table-bordered table-striped">
   <tr>
    <th width="10%">Image</th>
    <th width="35%">First Name</th>
    <th width="35%">Last Name</th>
    <th width="10%">Update</th>
    <th width="10%">Delete</th>
   </tr>
  ';
  if(mysqli_num_rows($result) > 0)
  {
   while($row = mysqli_fetch_object($result))
   {
    $output .= '
    <tr>
     <td><img src="upload/'.$row->image.'" class="img-thumbnail" width="50" height="35" /></td>
     <td>'.$row->first_name.'</td>
     <td>'.$row->last_name.'</td>
     <td><button type="button" name="update" id="'.$row->id.'" class="btn btn-success btn-xs update">Update</button></td>
     <td><button type="button" name="delete" id="'.$row->id.'" class="btn btn-danger btn-xs delete">Delete</button></td>
    </tr>
    ';
   }
  }
  else
  {
   $output .= '
    <tr>
     <td colspan="5" align="center">No Data Found</td>
    </tr>
   ';
  }
  $output .= '</table>';
  return $output;
 } 
 function upload_file($file)
 {
  if(isset($file))
  {
   $extension = explode('.', $file["name"]);
   $new_name = rand() . '.' . $extension[1];
   $destination = './upload/' . $new_name;
   move_uploaded_file($file['tmp_name'], $destination);
   return $new_name;
  }
 }

 function make_pagination_link($query, $record_per_page)
 {
  $output = '';
  $result = $this->execute_query($query);
  $total_records = mysqli_num_rows($result);
  $total_pages = ceil($total_records/$record_per_page);
  for($i=1; $i<=$total_pages; $i++)
  {
   $output .= '<span class="pagination_link" style="cursor:pointer; padding:6px; border:1px solid #ccc;" id="'.$i.'">'.$i.'</span>';
  }
  return $output;
 }
}
?>

index.php


<?php
//index.php
include 'crud.php';
$object = new Crud();
?>
<html>
 <head>
  <title>PHP Mysql Ajax Crud using OOPS - Pagination</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:1270px;
    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 Mysql Ajax Crud using OOPS - Pagination</h3><br /><br />
   <div class="col-md-8">
    <button type="button" name="add" id="add" class="btn btn-success" data-toggle="collapse" data-target="#user_collapse">Add</button>
   </div>
   <div class="col-md-4">
    <input type="text" name="search" id="search" placeholder="Search" class="form-control" />
   </div>
   <br />
   <br />
   <div id="user_collapse" class="collapse">
    <form method="post" id="user_form">
     <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" />
     <input type="hidden" name="hidden_user_image" id="hidden_user_image" />
     <span id="uploaded_image"></span>
     <br />
     <div align="center">
      <input type="hidden" name="action" id="action" />
      <input type="hidden" name="user_id" id="user_id" />
      <input type="submit" name="button_action" id="button_action" class="btn btn-default" value="Insert" />
     </div>
    </form>
   </div>
   <br /><br />
   <div id="user_table" class="table-responsive">
   </div>
  </div>
 </body>
</html>

<script type="text/javascript">
 $(document).ready(function(){

  load_data();

  $('#action').val("Insert");

  $('#add').click(function(){
   $('#user_form')[0].reset();
   $('#uploaded_image').html('');
   $('#button_action').val("Insert");
  });
  function load_data(page)
  {
   var action = "Load";
   $.ajax({
    url:"action.php",
    method:"POST",
    data:{action:action, page:page},
    success:function(data)
    {
     $('#user_table').html(data);
    }
   });
  }

  $(document).on('click', '.pagination_link', function(){
   var page = $(this).attr("id");
   load_data(page);
  });

  $('#user_form').on('submit', function(event){
   event.preventDefault();
   var firstName = $('#first_name').val();
   var lastName = $('#last_name').val();
   var extension = $('#user_image').val().split('.').pop().toLowerCase();
   if(extension != '')
   {
    if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
    {
     alert("Invalid Image File");
     $('#user_image').val('');
     return false;
    }
   }
   if(firstName != '' && lastName != '')
   {
    $.ajax({
     url:"action.php",
     method:"POST",
     data:new FormData(this),
     contentType:false,
     processData:false,
     success:function(data)
     {
      alert(data);
      $('#user_form')[0].reset();
      load_data();      
      $('#action').val("Insert");
      $('#button_action').val("Insert");
      $('#uploaded_image').html('');
     }
    })
   }
   else
   {
    alert("Both Fields are Required");
   }
  });

  $(document).on('click', '.update', function(){
   var user_id = $(this).attr("id");
   var action = "Fetch Single Data";
   $.ajax({
    url:"action.php",
    method:"POST",
    data:{user_id:user_id, action:action},
    dataType:"json",
    success:function(data)
    {
     $('.collapse').collapse("show");
     $('#first_name').val(data.first_name);
     $('#last_name').val(data.last_name);
     $('#uploaded_image').html(data.image);
     $('#hidden_user_image').val(data.user_image);
     $('#button_action').val("Edit");
     $('#action').val("Edit");
     $('#user_id').val(user_id);
    }
   });
  });
  
  $(document).on('click', '.delete', function(){
   var user_id = $(this).attr("id");
   var action = "Delete";
   if(confirm("Are you sure you want to delete this?"))
   {
    $.ajax({
     url:"action.php",
     method:"POST",
     data:{user_id:user_id, action:action},
     success:function(data)
     {
      alert(data);
      load_data();
     }
    });
   }
   else
   {
    return false;
   }
  });
  
  $('#search').keyup(function(){
   var query = $('#search').val();
   var action = "Search";
   if(query != '')
   {
    $.ajax({
     url:"action.php",
     method:"POST",
     data:{query:query, action:action},
     success:function(data)
     {
      $('#user_table').html(data);
     }
    });
   }
   else
   {
    load_data();
   }
  });
  
 });
</script>

action.php


<?php
//action.php
include 'crud.php';
$object = new Crud();
if(isset($_POST["action"]))
{
 if($_POST["action"] == "Load")
 {
  $record_per_page = 5;
  $page = '';

  if(isset($_POST["page"]))
  {
   $page = $_POST["page"];
  }
  else
  {
   $page = 1;
  }
  $start_from = ($page - 1) * $record_per_page;

  echo $object->get_data_in_table("SELECT * FROM users ORDER BY id DESC LIMIT $start_from, $record_per_page");
  echo '<br /><div align="center">';
  echo $object->make_pagination_link("SELECT * FROM users ORDER by id", $record_per_page);
  echo '</div><br />';

 }
 if($_POST["action"] == "Insert")
 {
  $first_name = mysqli_real_escape_string($object->connect, $_POST["first_name"]);
  $last_name = mysqli_real_escape_string($object->connect, $_POST["last_name"]);
  $image = $object->upload_file($_FILES["user_image"]);
  $query = "
  INSERT INTO users
  (first_name, last_name, image) 
  VALUES ('".$first_name."', '".$last_name."', '".$image."')
  ";
  $object->execute_query($query);
  echo 'Data Inserted';
 }
 if($_POST["action"] == "Fetch Single Data")
 {
  $output = '';
  $query = "SELECT * FROM users WHERE id = '".$_POST["user_id"]."'";
  $result = $object->execute_query($query);
  while($row = mysqli_fetch_array($result))
  {
   $output["first_name"] = $row['first_name'];
   $output["last_name"] = $row['last_name'];
   $output["image"] = '<img src="upload/'.$row['image'].'" class="img-thumbnail" width="50" height="35" />';
   $output["user_image"] = $row['image'];
  }
  echo json_encode($output);
 }

 if($_POST["action"] == "Edit")
 {
  $image = '';
  if($_FILES["user_image"]["name"] != '')
  {
   $image = $object->upload_file($_FILES["user_image"]);
  }
  else
  {
   $image = $_POST["hidden_user_image"];
  }
  $first_name = mysqli_real_escape_string($object->connect, $_POST["first_name"]);
  $last_name = mysqli_real_escape_string($object->connect, $_POST["last_name"]);
  $query = "UPDATE users SET first_name = '".$first_name."', last_name = '".$last_name."', image = '".$image."' WHERE id = '".$_POST["user_id"]."'";
  $object->execute_query($query);
  echo 'Data Updated';
  //echo $query;
 }
 
 if($_POST["action"] == "Delete")
 {
  $query = "DELETE FROM users WHERE id = '".$_POST["user_id"]."'";
  $object->execute_query($query);
  echo "Data Deleted";
 }
 
 if($_POST["action"] == "Search")
 {
  $search = mysqli_real_escape_string($object->connect, $_POST["query"]);
  $query = "
  SELECT * FROM users 
  WHERE first_name LIKE '%".$search."%' 
  OR last_name LIKE '%".$search."%' 
  ORDER BY id DESC
  ";
  //echo $query;
  echo $object->get_data_in_table($query);  
 }
 
}
?>

Friday, 23 December 2016

How to Create SEO Friendly URL in PHP with htaccess





In this post describe how to make Clean or Semantic or SEO Friendly URL with Mysql Table Dynamic Content by using .htaccess mod_rewrite in PHP Script. This post will explain how can we Rewrite Dynamic dirty url with id to Semantic URL in PHP with using .htaccess. Clean url will increase your web site presence on search engine like Google, yahoo, bing etc and it will improve ranking on Search Engines. If you want to make SEO Friendly or Clean or Semantic Url for your site, so first you want to enable Apache re-write_module at your wamp server. By enabling Apache rewrite_module you can make clean SEO friendly url from your dynamic dirty url by writing few lines of PHP code and .htaccess file. For Semantic url you want to create .htaccess file in your working folder.

Source Code


.htaccess


RewriteEngine On

RewriteRule ^post/([a-zA-Z0-9-/]+)$ post.php?post_url=$1
RewriteRule ^post/([a-zA-Z-0-9-]+)/ post.php?post_url=$1

index.php


<?php
$connect = mysqli_connect("localhost", "root", "", "test_db");
if(isset($_POST["submit_btn"]))
{
 //mysqli_real_escape_string() - mysqli_real_escape_string() function escapes special characters in a string for use in an SQL statement
 //htmlentities() - htmlentities() function converts special characters to HTML entities.
 $post_title = mysqli_real_escape_string($connect, $_POST["post_title"]);
 $post_text = mysqli_real_escape_string($connect, $_POST["post_text"]);
 $post_title = htmlentities($post_title);
 $post_text = htmlentities($post_text);
 $sql = "INSERT INTO tbl_post (post_title, post_text, post_url) VALUES ('".$post_title."', '".$post_text."', '".php_slug($post_title)."')";
 if(mysqli_query($connect, $sql))
 {
  header("location:post/".php_slug($post_title)."");
 }
}

function php_slug($string)
{
 $slug = preg_replace('/[^a-z0-9-]+/', '-', trim(strtolower($string)));
 return $slug;
}

?>
<html>
 <head>
  <title>Make SEO Friendly / Clean Url in PHP using .htaccess</title>
  <style>
  .container
  {
   width:700px;
   margin:0 auto;
   border:1px solid #ccc;
   padding:16px;
  }
  .form_text
  {
   width:100%;
   padding:6px;
  }
  </style>
 </head>
 <body>
  <div class="container">
   <h3 align="center">Make SEO Friendly / Clean Url in PHP using .htaccess</h3>
   
   <form name="submit_form" method="post">
    <p>Post Title
    <input type="text" name="post_title" class="form_text" maxlength="200" />
    </p>
    <p>Post Text
    <textarea name="post_text" class="form_text" rows="10"></textarea>
    </p>
    <p><input type="submit" name="submit_btn" value="Submit" />
   </form>
  </div>
 </body>
</html>

post.php


<?php
//post.php
$connect = mysqli_connect("localhost", "root", "", "test_db");
$post_url = $_GET["post_url"];

$sql = "SELECT * FROM tbl_post WHERE post_url = '".$post_url."'";
$result = mysqli_query($connect, $sql);


?>


<html>
 <head>
  <title>Make SEO Friendly / Clean Url in PHP using .htaccess</title>
  <style>
  .container
  {
   width:700px;
   margin:0 auto;
   border:1px solid #ccc;
   padding:16px;
  }
  .form_text
  {
   width:100%;
   padding:6px;
  }
  </style>
 </head>
 <body>
  <div class="container">
   <h3 align="center">Make SEO Friendly / Clean Url in PHP using .htaccess</h3>
   <?php
   if(mysqli_num_rows($result) > 0)
   {
    while($row = mysqli_fetch_array($result))
    {
     echo '<h3>'.$row["post_title"].'</h3>';
     echo '<p>'.$row["post_text"].'</p>';
    }
   }
   else
   {
    echo '404 Page';
   }
   
   ?>
   
  </div>
 </body>
</html>

Tuesday, 20 December 2016

PHP Mysql Ajax Crud using OOPS - Live Data Search



In this Ajax Crud system development part we have start discussing on Live Data Search by using Ajax Jquery method in Object Oriented PHP programming script. We can make a simple but very userful live Mysql Database Table data searching element by using the Ajax with PHP OOP, in which the search or filter data results will load on web page in html table format as we have starting type search query in search input textbox.

By using this type of feature we can search or filter large amount of data without page refresh because in this we have use Ajax request for search or filter data at server side in PHP OOP Script. In any web application searching is very important or most required functionality and if We have provide live searching of Mysql data then that will provide us fast search or filter data result on web page without page refresh.

This tutorial is one part of Ajax Crud System make by using Object Oriented PHP Script. In previous part we have already seen how to remove or delete data by using Ajax with PHP OOP Script. But here we have seen some new Advance topic like Live Data search by using Ajax with PHP Script.

<input type="text" name="search" id="search" placeholder="Search" class="form-control" />

For this on index.php page which we have already make, so on this page we have define one textbox, so we can type search query in this input field. In this textbox we have define "id=search". We will use attribute as a selector in jquery code.

$('#search').keyup(function(){
   var query = $('#search').val();
   var action = "Search";
   if(query != '')
   {
    $.ajax({
     url:"action.php",
     method:"POST",
     data:{query:query, action:action},
     success:function(data)
     {
      $('#user_table').html(data);
     }
    });
   }
   else
   {
    load_data();
   }
  });

After this we have write jquery code on search textbox keyup jquery event, in this jquery code we have use textbox "id=search" as selector, so when any one in search query in textbox then this code will execute and this code has send ajax request to "action.php" page, during sending ajax request, it has been send textbox value in query variable and one action variable data to "action.php" page. In Ajax Success callback function receiving filter data in table format from server and that data has been display on this "
" tag. So under this tag it will display filter data in table format.

        if($_POST["action"] == "Search")
 {
  $search = mysqli_real_escape_string($object->connect, $_POST["query"]);
  $query = "
  SELECT * FROM users 
  WHERE first_name LIKE '%".$search."%' 
  OR last_name LIKE '%".$search."%' 
  ORDER BY id DESC
  ";
  echo $object->get_data_in_table($query);
 }

This code we have write on "action.php" page and this code first check value of $_POST["action"] variable is equal to Search, this variable we have pass though ajax request to this page. If value equal to "Search" then it will execute if block of code and under this block first it will clean value of $_POST["action"] variable which is also we have pass using Ajax method. After clean value it will make on select query for search data by using LIKE Mysql operator. After making Search query we want to execute this so we have use $object->get_data_in_table($query) function, this function we have already make in Crud class in previous part. This function will execute query and return query result into html table format and that result we have send to Ajax request and it will display result on web page.

So, this is simple live mysql table data search system make by using Ajax Jquery method and Object Oriented Programming. If you have any query regarding this tutorial, please comment your query under comment box


Source Code


crud.php


<?php
class Crud
{
 public $connect;
 private $host = 'localhost';
 private $username = 'root';
 private $password = '';
 private $database = 'crud'; 

 function __construct()
 {
  $this->database_connect();
 }

 public function database_connect()
 {
  $this->connect = mysqli_connect($this->host, $this->username, $this->password, $this->database);
 }

 public function execute_query($query)
 {
  return mysqli_query($this->connect, $query);
 }

 public function get_data_in_table($query)
 {
  $output = '';
  $result = $this->execute_query($query);
  $output .= '
  <table class="table table-bordered table-striped">
   <tr>
    <th width="10%">Image</th>
    <th width="35%">First Name</th>
    <th width="35%">Last Name</th>
    <th width="10%">Update</th>
    <th width="10%">Delete</th>
   </tr>
  ';
  if(mysqli_num_rows($result) > 0)
  {
   while($row = mysqli_fetch_object($result))
   {
    $output .= '
    <tr>
     <td><img src="upload/'.$row->image.'" class="img-thumbnail" width="50" height="35" /></td>
     <td>'.$row->first_name.'</td>
     <td>'.$row->last_name.'</td>
     <td><button type="button" name="update" id="'.$row->id.'" class="btn btn-success btn-xs update">Update</button></td>
     <td><button type="button" name="delete" id="'.$row->id.'" class="btn btn-danger btn-xs delete">Delete</button></td>
    </tr>
    ';
   }
  }
  else
  {
   $output .= '
    <tr>
     <td colspan="5" align="center">No Data Found</td>
    </tr>
   ';
  }
  $output .= '</table>';
  return $output;
 }
 
 function upload_file($file)
 {
  if(isset($file))
  {
   $extension = explode('.', $file['name']);
   $new_name = rand() . '.' . $extension[1];
   $destination = './upload/' . $new_name;
   move_uploaded_file($file['tmp_name'], $destination);
   return $new_name;
  }
 }
}
?>

index.php


<?php
include 'crud.php';
$object = new Crud();
?>
<html>
 <head>
  <title>PHP Mysql Ajax Crud using OOPS - Live Data Search</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:1270px;
    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 Mysql Ajax Crud using OOPS - Live Data Search</h3><br /><br />
   <div class="col-md-8">
    <button type="button" name="add" id="add" class="btn btn-success" data-toggle="collapse" data-target="#user_collapse">Add</button>
   </div>
   <div class="col-md-4">
    <input type="text" name="search" id="search" placeholder="Search"  class="form-control" />
   </div>
   <br />
   <br />
   <div id="user_collapse" class="collapse">
    <form method="post" id="user_form">
     <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" />
     <input type="hidden" name="hidden_user_image" id="hidden_user_image" />
     <span id="uploaded_image"></span>
     <br />
     <div align="center">
      <input type="hidden" name="action" id="action" />
      <input type="hidden" name="user_id" id="user_id" />
      <input type="submit" name="button_action" id="button_action" class="btn btn-default" value="Insert" />
     </div>
     <br />
    </form>
   </div>
   <br />
   <div class="table-responsive" id="user_table">
    
   </div>
  </div>
 </body>
</html>

<script type="text/javascript">
 $(document).ready(function(){
  
  load_data();
  $('#action').val("Insert");
  $('#add').click(function(){
   $('#user_form')[0].reset();
   $('#uploaded_image').html('');
   $('#button_action').val("Insert");
  });
  function load_data()
  {
   var action = "Load";
   $.ajax({
    url:"action.php",
    method:"POST",
    data:{action:action},
    success:function(data)
    {
     $('#user_table').html(data);
    }
   });
  }
  
  $('#user_form').on('submit', function(event){
   event.preventDefault();
   var firstName = $('#first_name').val();
   var lastName = $('#last_name').val();
   var extension = $('#user_image').val().split('.').pop().toLowerCase();
   if(extension != '')
   {
    if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
    {
     alert("Invalid Image File");
     $('#user_image').val('');
     return false;
    }
   }
   if(firstName != '' && lastName != '')
   {
    $.ajax({
     url:"action.php",
     method:'POST',
     data:new FormData(this),
     contentType:false,
     processData:false,
     success:function(data)
     {
      alert(data);
      $('#user_form')[0].reset();
      load_data();
      $("#action").val("Insert");
      $('#button_action').val("Insert");
      $('#uploaded_image').html('');
     }
    });
   }
   else
   {
    alert("Both Fields are Required");
   }
  });

  $(document).on('click', '.update', function(){
   var user_id = $(this).attr("id");
   var action = "Fetch Single Data";
   $.ajax({
    url:"action.php",
    method:"POST",
    data:{user_id:user_id, action:action},
    dataType:"json",
    success:function(data)
    {
     $('.collapse').collapse("show");
     $('#first_name').val(data.first_name);
     $('#last_name').val(data.last_name);
     $('#uploaded_image').html(data.image);
     $('#hidden_user_image').val(data.user_image);
     $('#button_action').val("Edit");
     $('#action').val("Edit");
     $('#user_id').val(user_id);
    }
   });
  });
  $(document).on('click', '.delete', function(){
   var user_id = $(this).attr("id");
   var action = "Delete";
   if(confirm("Are you sure you want to delete this?"))
   {
    $.ajax({
     url:"action.php",
     method:"POST",
     data:{user_id:user_id, action:action},
     success:function(data)
     {
      alert(data);
      load_data();
     }
    });
   }
   else
   {
    return false;
   }
  });
  
  $('#search').keyup(function(){
   var query = $('#search').val();
   var action = "Search";
   if(query != '')
   {
    $.ajax({
     url:"action.php",
     method:"POST",
     data:{query:query, action:action},
     success:function(data)
     {
      $('#user_table').html(data);
     }
    })
   }
   else
   {
    load_data();
   }
  });
 });
</script>

action.php


<?php
include 'crud.php';
$object = new Crud();
if(isset($_POST["action"]))
{
 if($_POST["action"] == "Load")
 {
  echo $object->get_data_in_table("SELECT * FROM users ORDER BY id DESC");
 }
 if($_POST["action"] == "Insert")
 {
  $first_name = mysqli_real_escape_string($object->connect, $_POST["first_name"]);
  $last_name = mysqli_real_escape_string($object->connect, $_POST["last_name"]);
  $image = $object->upload_file($_FILES["user_image"]);
  $query = "
  INSERT INTO users
  (first_name, last_name, image) 
  VALUES ('".$first_name."', '".$last_name."', '".$image."')";
  $object->execute_query($query);
  echo 'Data Inserted'; 
 }
 if($_POST["action"] == "Fetch Single Data")
 {
  $output = '';
  $query = "SELECT * FROM users WHERE id = '".$_POST["user_id"]."'";
  $result = $object->execute_query($query);
  while($row = mysqli_fetch_array($result))
  {
   $output["first_name"] = $row['first_name'];
   $output["last_name"] = $row['last_name'];
   $output["image"] = '<img src="upload/'.$row['image'].'" class="img-thumbnail" width="50" height="35" />';
   $output["user_image"] = $row['image'];
  }
  echo json_encode($output);
 }

 if($_POST["action"] == "Edit")
 {
  $image = '';
  if($_FILES["user_image"]["name"] != '')
  {
   $image = $object->upload_file($_FILES["user_image"]);
  }
  else
  {
   $image = $_POST["hidden_user_image"];
  }
  $first_name = mysqli_real_escape_string($object->connect, $_POST["first_name"]);
  $last_name = mysqli_real_escape_string($object->connect, $_POST["last_name"]);
  $query = "UPDATE users SET first_name = '".$first_name."', last_name = '".$last_name."', image = '".$image."' WHERE id = '".$_POST["user_id"]."'";
  $object->execute_query($query);
  echo 'Data Updated';
 }
 if($_POST["action"] == "Delete")
 {
  $query = "DELETE FROM users WHERE id = '".$_POST["user_id"]."'";
  $object->execute_query($query);
  echo 'Data Deleted';
 }
 if($_POST["action"] == "Search")
 {
  $search = mysqli_real_escape_string($object->connect, $_POST["query"]);
  $query = "
  SELECT * FROM users 
  WHERE first_name LIKE '%".$search."%' 
  OR last_name LIKE '%".$search."%' 
  ORDER BY id DESC
  ";
  echo $object->get_data_in_table($query);
 }
}
?>