Monday, 7 January 2019

Twitter Like Follow Unfollow System in PHP using Ajax jQuery



From this post, you can learn how to make Follow and Unfollow system like Twitter which you can create in PHP using Ajax jQuery Mysql and Bootstrap. There are many viewers has requested to use PHP to build a Twitter like system. If you know on Twitter can post short News in Tweets format, and that tweets will be visible to those Twitter user who has follow this share user. When user share any news or tweets, that will be visible to his followers. So, this type of system we will make in PHP using Ajax jQuery and Mysql Database.

IF you are looking for any Social Networking Application for you colleage project, Then this post will help you to make small Follow Unfollow Application in PHP using Ajax step by step. On every publish of video tutorial of this post, you can find updated source code under this post. So, here we will show you How to develop twitter like follow and Unfollow system using Ajax in PHP script. Because most of this Social Networking sites are make in PHP Ajax. Here we have also use Bootstrap library for CSS purpose for make this system. So, here we will make dynamic follow unfollow application in PHP using Ajax.

Following are the main functionality of this follow unfollow system.

  • New User Registration
  • Login form for registered user
  • Authenticated User can edit his or here profile with upload profile image
  • User can share post, and list post
  • List User with follow unfollow button
  • Display number of followers of each user
  • Main functionality is to follow or unfollow other user post
  • Display dynamic results will be display if user click on follow unfollo button
  • All data will display using Ajax without refresh of web page
  • If you user follow any user, then he can also unfollow that user again

So, Above are the main functionality of this follow unfollow system in PHP using Ajax jQuery Mysql and Bootstrap. Below you can find source code of Ajax based follow unfollow system.





Source Code


Database


Run follow SQL script, it will make three table like tbl_twitter_user, tbl_samples_post and tbl_follow in your PHPMysqmin. Follow Unfollow system has been use this three table for make application.


CREATE TABLE `tbl_follow` (
  `follow_id` int(11) NOT NULL AUTO_INCREMENT,
  `sender_id` int(11) NOT NULL,
  `receiver_id` int(11) NOT NULL,
  PRIMARY KEY (`follow_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

CREATE TABLE `tbl_samples_post` (
  `post_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `post_content` text NOT NULL,
  `post_datetime` datetime NOT NULL,
  PRIMARY KEY (`post_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

CREATE TABLE `tbl_twitter_user` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(150) NOT NULL,
  `password` varchar(150) NOT NULL,
  `name` varchar(150) NOT NULL,
  `profile_image` varchar(150) NOT NULL,
  `bio` text NOT NULL,
  `follower_number` int(11) NOT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;


database_connection.php


This PHP file is used for make database connection. This is common file which we will used in all files for make Mysql Database connection.


<?php

//database_connection.php

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

?>







register.php


For any dynamic web application, we have to first make register form. So, here also first we want to make user registration system. So, new user can register into system. So, for make any dynamic system, here we have make this register form. In this system, here we have validate username already exists or not. If username already exists then user cannot register into system. In this registration system we have also validate user password by re-entering password. So, this is basic validation, which we have use here for make registration system for Follow Unfollow system using PHP with Ajax jQuery Mysql and Bootstrap.


<!--
//register.php
!-->

<?php

include('database_connection.php');

session_start();

$message = '';

if(isset($_SESSION['user_id']))
{
 header('location:index.php');
}

if(isset($_POST['register']))
{
 $username = trim($_POST["username"]);
 $password = trim($_POST["password"]);
 $check_query = "
 SELECT * FROM tbl_twitter_user 
 WHERE username = :username
 ";
 $statement = $connect->prepare($check_query);
 $check_data = array(
  ':username'  => $username
 );
 if($statement->execute($check_data))
 {
  if($statement->rowCount() > 0)
  {
   $message .= '<p><label>Username already taken</label></p>';
  }
  else
  {
   if(empty($username))
   {
    $message .= '<p><label>Username is required</label></p>';
   }
   if(empty($password))
   {
    $message .= '<p><label>Password is required</label></p>';
   }
   else
   {
    if($password != $_POST["confirm_password"])
    {
     $message .= '<p><label>Password not match</label></p>';
    }
   }
   if($message == '')
   {
    $data = array(
     ':username'  => $username,
     ':password'  => password_hash($password, PASSWORD_DEFAULT)
    );

    $query = "
    INSERT INTO tbl_twitter_user 
    (username, password) 
    VALUES (:username, :password)
    ";

    $statement = $connect->prepare($query);

    if($statement->execute($data))
    {
     $message = '<label>Registration Completed</label>';
    }
   }
  }
 }
}

?>

<html>  
    <head>  
        <title>Twitter Like Follow Unfollow System in PHP using Ajax jQuery</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    </head>  
    <body>  
        <div class="container">
   <br />
   
   <h3 align="center">Twitter Like Follow Unfollow System in PHP using Ajax jQuery</a></h3><br />
   <br />
   <div class="panel panel-default">
      <div class="panel-heading">Register</div>
    <div class="panel-body">
     <form method="post">
      <span class="text-danger"><?php echo $message; ?></span>
      <div class="form-group">
       <label>Enter Username</label>
       <input type="text" name="username" class="form-control" />
      </div>
      <div class="form-group">
       <label>Enter Password</label>
       <input type="password" name="password" id="password" class="form-control" />
      </div>
      <div class="form-group">
       <label>Re-enter Password</label>
       <input type="password" name="confirm_password" id="confirm_password" class="form-control" />
      </div>
      <div class="form-group">
       <input type="submit" name="register" class="btn btn-info" value="Register" />
      </div>
      <div align="center">
       <a href="login.php">Login</a>
      </div>
     </form>
    </div>
   </div>
  </div>
    </body>  
</html>


login.php


Once you have make registration system in Follow Unfollow application. After registration you have to make login page for authenticate user login details like username and password. Here password will be validate by using password_hash() method. Because at the time registration we have store password in hash format. If user has enter proper details, then his for validate user is login or not in whole system, we have store user details under $_SESSION variable.


<!--
//login.php
!-->

<?php

include('database_connection.php');

session_start();

$message = '';

if(isset($_SESSION['user_id']))
{
 header('location:index.php');
}

if(isset($_POST["login"]))
{
 $query = "
 SELECT * FROM tbl_twitter_user 
    WHERE username = :username
 ";
 $statement = $connect->prepare($query);
 $statement->execute(
  array(
      ':username' => $_POST["username"]
     )
 );
 $count = $statement->rowCount();
 if($count > 0)
 {
  $result = $statement->fetchAll();
  foreach($result as $row)
  {
   if(password_verify($_POST['password'], $row['password']))
   {
    $_SESSION['user_id'] = $row['user_id'];
    $_SESSION['username'] = $row['username'];
    header('location:index.php');
   }
   else
   {
    $message = '<label>Wrong Password</label>';
   }
  }
 }
 else
 {
  $message = '<label>Wrong Username</labe>';
 }
}


?>

<html>  
    <head>  
        <title>Twitter Like Follow Unfollow System in PHP using Ajax jQuery</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    </head>  
    <body>  
        <div class="container">
   <br />
   
   <h3 align="center">Twitter Like Follow Unfollow System in PHP using Ajax jQuery</a></h3><br />
   <br />
   <div class="panel panel-default">
      <div class="panel-heading">Login</div>
    <div class="panel-body">
     <form method="post">
      <p class="text-danger"><?php echo $message; ?></p>
      <div class="form-group">
       <label>Enter Username</label>
       <input type="text" name="username" class="form-control" required />
      </div>
      <div class="form-group">
       <label>Enter Password</label>
       <input type="password" name="password" class="form-control" required />
      </div>
      <div class="form-group">
       <input type="submit" name="login" class="btn btn-info" value="Login" />
      </div>
      <div align="center">
       <a href="register.php">Register</a>
      </div>
     </form>
    </div>
   </div>
  </div>
    </body>  
</html>


index.php


If system is validated user information, and it is correct then page will be redirect to index.php page. From this page user can share his or her post. User can view his or her post along with post of follow user by login user. On index page user can view all user list with follow and unfollow button. Most of all operation of follow and unfollow system will be done on this page. This page will be view to only login user.


<!--
//index.php
!-->

<?php

include('database_connection.php');

session_start();

if(!isset($_SESSION['user_id']))
{
 header('location:login.php');
}
?>

<html>  
    <head>  
        <title>Twitter Like Follow Unfollow System in PHP using Ajax jQuery</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.2.2/jquery.form.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    </head>  
    <body>  
        <div class="container">
   <?php
   include("menu.php");
   ?>
   <div class="row">
    <div class="col-md-8">
     <div class="panel panel-default">
      <div class="panel-heading">
       <h3 class="panel-title">Start Write Here</h3>
      </div>
      <div class="panel-body">
       <form method="post" id="post_form">
        <div class="form-group">
         <textarea name="post_content" id="post_content" maxlength="160" class="form-control" placeholder="Write your short story"></textarea>
        </div>
        <div class="form-group" align="right">
         <input type="hidden" name="action" value="insert" />
         <input type="submit" name="share_post" id="share_post" class="btn btn-primary" value="Share" />
        </div>
       </form>
      </div>
     </div>
     <div class="panel panel-default">
      <div class="panel-heading">
       <h3 class="panel-title">Trending Now</h3>
      </div>
      <div class="panel-body">
       <div id="post_list">
       
       </div>
      </div>
     </div>
    </div>
    <div class="col-md-4">
     <div class="panel panel-default">
      <div class="panel-heading">
       <h3 class="panel-title">User List</h3>
      </div>
      <div class="panel-body">
       <div id="user_list"></div>
      </div>
     </div>
    </div>
   </div>
  </div>
    </body>  
</html>

<script>  
$(document).ready(function(){
 
 fetch_post();
 fetch_user();
 
 function fetch_post()
 {
  var action = 'fetch_post';
  $.ajax({
   url:"action.php",
   method:"POST",
   data:{action:action},
   success:function(data)
   {
    $('#post_list').html(data);
   }
  });
 }
 
 function fetch_user()
 {
  var action = 'fetch_user';
  $.ajax({
   url:"action.php",
   method:"POST",
   data:{action:action},
   success:function(data)
   {
    $('#user_list').html(data);
   }
  });
 }

 $('#post_form').on('submit', function(event){
  event.preventDefault();
  if($('#post_content').val() == '')
  {
   alert("Enter Story Content");
  }
  else
  {
   var form_data = $(this).serialize();
   $.ajax({
    url:"action.php",
    method:"POST",
    data:form_data,
    success:function(data)
    {
     alert("Post has been shared");
     $('#post_form')[0].reset();
     fetch_post();
    }
   })
  }
 });
});  
</script>


menu.php


This file is used for make dynamic menu, here user name will be display by using $_SESSION varibale. Here in this we have add two menu for go to profile page and logout page.


                        <br />
   <nav class="navbar navbar-inverse">
    <div class="container-fluid">
     <div class="navbar-header">
      <a class="navbar-brand" href="index.php">Webslesson</a>
     </div>
     <ul class="nav navbar-nav navbar-right">
      <li class="dropdown">
       <a class="dropdown-toggle" data-toggle="dropdown" href="#"><?php echo $_SESSION['username']; ?>
       <span class="caret"></span></a>
       <ul class="dropdown-menu">
        <li><a href="profile.php">Profile</a></li>
        <li><a href="logout.php">Logout</a></li>
       </ul>
      </li>
     </ul>
    </div>
   </nav>


logout.php


If user want to logout from dynamic follow unfollow application, so when user click on logout link then page will redirect to this page, and on this page all $_SESSION variable will be destroy using session_destroy() function.


<?php

//logout.php

session_start();

session_destroy();

header('location:login.php');

?>


profile.php


This file is used for edit user profile details in follow unfollow application by using PHP. Here user not only edit their profile details like username, password, name and short bio but also user can change profile image by upload image file under images folder. This image and user name will be display to other user.


<!--
//profile.php
!-->

<?php

include('database_connection.php');

session_start();

if(!isset($_SESSION['user_id']))
{
 header('location:login.php');
}

$message = '';

if(isset($_POST['edit_profile']))
{
 $file_name = '';
 if(isset($_POST['profile_image']))
 {
  $file_name = $_POST['profile_image'];
 }

 if($_FILES['profile_image']['name'] != '')
 {
  if($file_name != '')
  {
   unlink('images/'.$file_name);
  }
  $image_name = explode(".", $_FILES['profile_image']['name']);
  $extension = end($image_name);
  $temporary_location = $_FILES['profile_image']['tmp_name'];
  $file_name = rand() . '.' . strtolower($extension);
  $location = 'images/' . $file_name;
  move_uploaded_file($temporary_location, $location);
 }
 $check_query = "
 SELECT * FROM tbl_twitter_user WHERE username = :username AND user_id != :user_id
 ";
 $statement = $connect->prepare($check_query);
 $statement->execute(
  array(
   ':username'  =>  trim($_POST["username"]),
   ':user_id'  =>  $_SESSION["user_id"]
  )
 );
 $total_row = $statement->rowCount();
 if($total_row > 0)
 {
  $message = '<div class="alert alert-danger">Username Already Exists</div>';
 }
 else
 {
  $data = array(
   ':username'   => trim($_POST["username"]),
   ':name'    => trim($_POST["name"]),
   ':profile_image' => $file_name,
   ':bio'    => trim($_POST["bio"]),
   ':user_id'   => $_SESSION["user_id"]
  );
  if($_POST['password'] != '')
  {
   $data[] = array(
    ':password'  => password_hash($_POST["password"], PASSWORD_DEFAULT)
   );
   $query = '
   UPDATE tbl_twitter_user SET username = :username, password = :password, name = :name, profile_image = :profile_image, bio = :bio WHERE user_id = :user_id
   ';
  }
  else
  {
   $query = '
   UPDATE tbl_twitter_user SET username = :username, name = :name, profile_image = :profile_image, bio = :bio WHERE user_id = :user_id
   ';
  }
  $statement = $connect->prepare($query);
  if($statement->execute($data))
  {
   $message = '<div class="alert alert-success">Profile Updated</div>';
  }
 }
}



$query = "SELECT * FROM tbl_twitter_user WHERE user_id = '".$_SESSION["user_id"]."'";

$statement = $connect->prepare($query);

$statement->execute();

$result = $statement->fetchAll();

?>

<html>  
    <head>  
        <title>Twitter Like Follow Unfollow System in PHP using Ajax jQuery</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.2.2/jquery.form.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    </head>  
    <body>  
        <div class="container">
   <?php 
   include('menu.php');
   ?>
   <div class="row">
    <div class="col-md-3">
    
    </div>
    <div class="col-md-6">
     <div class="panel panel-default">
      <div class="panel-heading">
       <h3 class="panel-title">Edit Profile</h3>
      </div>
      <div class="panel-body">
       <?php
       foreach($result as $row)
       {
        echo $message;
       ?>
       <form method="post" enctype="multipart/form-data">
        <div class="form-group">
         <label>Username</label>
         <input type="text" name="username" id="username" pattern="^[a-zA-Z0-9_.-]*$" required class="form-control" value="<?php echo $row["username"];?>" />
        </div>
        <div class="form-group">
         <label>Password</label>
         <input type="password" name="password" id="password" class="form-control" />
        </div>
        <div class="form-group">
         <label>Name</label>
         <input type="text" name="name" id="name" class="form-control" required value="<?php echo $row["name"]; ?>" />
        </div>
        <div class="form-group">
         <label>Profile Image</label>
         <input type="file" name="profile_image" id="profile_image" accept="image/*" />
         <?php
         if($row["profile_image"] != '')
         {
          echo '<img src="images/'.$row["profile_image"].'" class="img-thumbnail" width="150" />';
          echo '<input type="hidden" name="profile_image" value="'.$row["profile_image"].'" />';
         }
         ?>
        </div>
        <div class="form-group">
         <label>Short Bio</label>
         <textarea name="bio" id="bio" class="form-control"><?php echo $row["bio"]; ?></textarea>
        </div>
        <div class="form-group">
         <input type="submit" name="edit_profile" id="edit_profile" class="btn btn-primary" value="Save" />
        </div>
       </form>
       <?php
       }
       ?>
      </div>
     </div>
    </div>
    <div class="col-md-3">
    
    </div>
   </div>
  </div>
    </body>  
</html>


action.php


This file is used for perform all core operation of Insert Post, Fetch post data, fetch user data and make follow unfollow button in PHP Follow Unfollow system. This file will received request for all above operation.


<?php

//action.php

include('database_connection.php');

session_start();

if(isset($_POST["action"]))
{
 $output = '';
 if($_POST["action"] == 'fetch_post')
 {
  $query = "
  SELECT * FROM tbl_samples_post 
  LEFT JOIN tbl_twitter_user ON tbl_twitter_user.user_id = tbl_samples_post.user_id 
        WHERE tbl_samples_post.user_id = '&quot;.$_SESSION[&quot;user_id&quot;].&quot;'
  GROUP BY tbl_samples_post.post_id 
  ORDER BY post_id DESC";
  
  $statement = $connect->prepare($query);
  $statement->execute();
  $result = $statement->fetchAll();
  $total_row = $statement->rowCount();
  
  if($total_row > 0)
  {
   foreach($result as $row)
   {
    $profile_image = '';
    if($row["profile_image"] != '')
    {
     $profile_image = '<img src="images/'.$row["profile_image"].'" class="img-thumbnail img-responsive" />';
    }
    else
    {
     $profile_image = '<img src="images/user.jpg" class="img-thumbnail img-responsive" />';
    }
    $output .= '
    <div class="jumbotron" style="padding:24px 30px 24px 30px">
     <div class="row">
      <div class="col-md-2">
       '.$profile_image.'
      </div>
      <div class="col-md-10">
       <h3><b>@'.$row["username"].'</b></h3>
       <p>'.$row["post_content"].'
       <button type="button" class="btn btn-link post_comment" id="'.$row["post_id"].'" data-user_id="'.$row["user_id"].'">Comment</button>
       </p>
       <div id="comment_form'.$row["post_id"].'" style="display:none;">
        <div class="form-group">
         <textarea name="comment" class="form-control" id="comment'.$row["post_id"].'"></textarea>
        </div>
        <div class="form-group" align="right">
         <button type="button" name="submit_comment" class="btn btn-primary btn-xs submit_comment" data-post_id="'.$row["post_id"].'">Comment</button>
        </div>
       </div>
      </div>
     </div>
    </div>
    ';
   }
  }
  else
  {
   $output = '<h4>No Post Found</h4>';
  }

  echo $output;
 }
 
 if($_POST["action"] == 'insert')
 {
  $data = array(
   ':user_id'   => $_SESSION["user_id"],
   ':post_content'  => $_POST["post_content"],
   ':post_datetime' => date("Y-m-d") . ' ' . date("H:i:s", STRTOTIME(date('h:i:sa')))
  );
  $query = "
  INSERT INTO tbl_samples_post 
  (user_id, post_content, post_datetime) 
  VALUES (:user_id, :post_content, :post_datetime)";
  
  $statement = $connect->prepare($query);
  $statement->execute($data);
 }
 
 if($_POST["action"] == 'fetch_user')
 {
  $query = "SELECT * FROM tbl_twitter_user WHERE user_id != '".$_SESSION["user_id"]."' ORDER BY user_id DESC";
  $statement = $connect->prepare($query);
  $statement->execute();
  $result = $statement->fetchAll();
  foreach($result as $row)
  {
   $profile_image = '';
   if($row["profile_image"] != '')
   {
    $profile_image = '<img src="images/'.$row["profile_image"].'" class="img-thumbnail img-responsive" />';
   }
   else
   {
    $profile_image = '<img src="images/user.jpg" class="img-thumbnail img-responsive" />';
   }
   $output .= '
   <div class="row">
    <div class="col-md-4">
     '.$profile_image.'
    </div>
    <div class="col-md-8">
     <h4><b>@'.$row["username"].'</b></h4>
     '.make_follow_button($connect, $row["user_id"], $_SESSION["user_id"]).'
     <span class="label label-success">'.$row["follower_number"].' Followers</span>
    </div>
   </div>
   <hr />
   ';
  }
  echo $output;
 }
}

function make_follow_button($connect, $sender_id, $receiver_id)
{
 $query = "SELECT * FROM tbl_follow WHERE sender_id = '".$sender_id."' AND receiver_id = '".$receiver_id."'";
 $statement = $connect->prepare($query);
 $statement->execute();
 $total_row = $statement->rowCount();
 $output = '';
 if($total_row > 0)
 {
  $output = '<button type="button" name="follow_button" class="btn btn-warning action_button" data-action="unfollow" data-sender_id="'.$sender_id.'"> Following</button>';
 }
 else
 {
  $output = '<button type="button" name="follow_button" class="btn btn-info action_button" data-action="follow" data-sender_id="'.$sender_id.'"><i class="glyphicon glyphicon-plus"></i> Follow</button>';
 }
 return $output;
}




?>


Remaining source code will be added very shortly.



Thursday, 3 January 2019

PHP: Trends to watch out in 2019



When it comes to PHP website development, the developers feel quite comfortable in comparison to other programming languages since it helps to assist on one particular area at a time. PHP is also widely popular because it is an open source programming language meaning it is free to use and supports MS SQL, MySQL and Oracle databases without any errors. Taking into consideration such good qualities, we can expect to see a rising growth in PHP development.

Let us look at some of the trends which are going to raise the PHP development in the upcoming years.

#1 Great choice for Startups and Businesses


For creating enterprise applications, PHP language is well-suited as it can easily handle a large volume of data. Initially, you can start as a Minimum Viable Product by utilizing PHP and then keep up growing. Being open source, it comes with ready to use bundles and libraries making it less vulnerable to different changes in the field of website development.

#2 JAVA + PHP


It is possibly expected in the future to create applications combining of both Java and PHP. Developers prefer this combination as Java is most secured programming language while PHP provides speed. With the combined use, the companies essentially reduce the costs and upgrade their applications within a relatively shorter period of time.

#3 Merge with IOT technology


A complex virtual structure of three distinct layer that needs a dynamic language which also provides faster coding is the IOT technology. All these requirements are best fitted in PHP to make the best possible infrastructure solutions. Also, the latest version of PHP allows the developers to easily access the asynchronous programming which easily carries out OHO code to different multiple tasks in one particular single script.

#4 Flexible Usage


When you have already built a web application for your business and wish to further expand it, you can actually choose to borrow different libraries from various places. This requires a middleware in such cases. Middleware is sort of bridge between the OS or database and web applications as you can easily use it to access any of the PHP framework libraries.

#5 User Interface


Another major PHP trend for the user interface is responsive web used by social media websites like Facebook, Twitter, Emails and even e-commerce like Amazon, Flipkart etc. To make these websites more convenient to the user and offer the best experience, the owners should ensure that the websites are responsive.

Other rising trends like infographics, online presentations, and visual effects keep the user engaged with the website. Nowadays, to create a 3D interaction like games or banner ads Flash is used; Parallax scrolling is another gaming trends to provide the images and banners with a 3D effect.




Exciting times ahead…


We can conclude that PHP is highly dynamic for creating dynamic websites easily. It can also be easily packaged with all types of Linux distributions which are easy to run with two distinct commands on the given command line. Such cost-effective benefits and facets of PHP will become an ideal choice for businesses and shape the website development industry in the upcoming years.

Author Bio:


Diana Vantur is a Technology Analyst currently working at Tatvasoft UK which is a PHP development company in UK. Her area of interest includes tech news and how software is being used in trending business. She strongly believes that knowledge is meant to be shared - whether related to design, software, technologies, and the list goes on.

Friday, 28 December 2018

Codeigniter Ajax CRUD Application using jQuery Bootgrid

If you have looking for make Single Page CRUD application in Codeigniter using Ajax, then this post will help you. Because in this post you can learn step by step or from scratch how to use jQuery Bootgrid plugin in Codeigniter with Ajax. jQuery Bootgrid plugin is a lightweight plugin, which is flexible, powerful grid plugin for load dynamic data using Ajax, it is also very customizable grid control mainly if you have use Bootstrap library. It is mainly used for display dynamic data using Ajax.


By using this plugin you can get following benifits:


  • Simple Header or Footer Navigation
  • Soriting Table Column Data
  • Live Searching or Filtering of Data
  • Pagination
  • Client Side Processing and Server Side Processing of Data

Once of our previouse post in which we have already covered jQuery Bootgrid Server Side Processing in PHP using Ajax. But here we have seen how to integrate Bootgrid Grid Plugin in Codeigniter Framework. Becase Codeigniter is PHP MVC framework, which is widely used by many web developers for their web development. So, If you are Codeigniter Web Developer then you have to know How to use Bootgrid Plugin with Codeigniter application. For this here we have make this tutorial. In this post we will Covered following CRUD operation with jQuery Bootgrid in Codeigniter using Ajax.


  • Do Server Side Processing and Load Data in jQuery Bootgrid Plugin in Codeigniter using Ajax
  • Add or Insert Data into Mysql in Codeigniter using Ajax with jQuery Bootgrid & Bootstrap Modal
  • Edit or Update Mysql Data in Codeigniter using Ajax with jQuery Bootgrid & Bootstrap Modal
  • Delete or Remove Data from Mysql in Codeigniter using Ajax with jQuery Bootgrid & Bootstrap Modal








Bootgrid.php(Controller)


First We have to make Bootgrid.php Controller under application/controllers folder. This class is mainly used for handle http request for perform Insert, Update, Delete and Read data Request. In this class, you can find following function.


index() - This is root function for this class, when in browser, we have write base url with this class then this function has been called. This function has load bootgrid.php view as output on browser.


fetch_data() - This function is received Ajax request from Bootgrid plugin for fetch data from mysql data. This function will convert data into Array format, and send to Bootgrid Ajax request in json string formate.


action() - This function is used for insert or add into mysql table using ajax. Because this function has received ajax request for insert data into mysql table.


fetch_single_data() - This function mainly fetch particular employee details based on value of employee id. This is for edit existing employee details.

delete_data() - This function is used for handle Ajax delete data request from jQuery Bootgrid Plugin in Codeigniter.



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

class Bootgrid extends CI_Controller {
 
 public function __construct()
 {
  parent::__construct();
  $this->load->model('bootgrid_model');
 }

 function index()
 {
  $this->load->view('bootgrid');
 }

 function fetch_data()
 {
  $data = $this->bootgrid_model->make_query();
  $array = array();
  foreach($data as $row)
  {
   $array[] = $row;
  }
  $output = array(
   'current'  => intval($_POST["current"]),
   'rowCount'  => 10,
   'total'   => intval($this->bootgrid_model->count_all_data()),
   'rows'   => $array
  );
  echo json_encode($output);
 }

 function action()
 {
  if($this->input->post('operation'))
  {
   $data = array(
    'name'   => $this->input->post('name'),
    'address'  => $this->input->post('address'),
    'gender'  => $this->input->post('gender'),
    'designation' => $this->input->post('designation'),
    'age'   => $this->input->post('age')
   );
   if($this->input->post('operation') == 'Add')
   {
    $this->bootgrid_model->insert($data);
    echo 'Data Inserted';
   }
   if($this->input->post('operation') == 'Edit')
   {
    $this->bootgrid_model->update($data, $this->input->post('employee_id'));
    echo 'Data Updated';
   }
  }
 }

 function fetch_single_data()
 {
  if($this->input->post('id'))
  {
   $data = $this->bootgrid_model->fetch_single_data($this->input->post('id'));
   foreach($data as $row)
   {
    $output['name'] = $row['name'];
    $output['address'] = $row['address'];
    $output['gender'] = $row['gender'];
    $output['designation'] = $row['designation'];
    $output['age'] = $row['age'];
   }
   echo json_encode($output);
  }
 }

 function delete_data()
 {
  if($this->input->post('id'))
  {
   $this->bootgrid_model->delete($this->input->post('id'));
   echo 'Data Deleted';
  }
 }
}

?>





Bootgrid_model.php(Models)


This class we have to make under application/models folder. This model class is mainly used for all type of database operation. In this class we have make following function for perform database related operation.


make_query() - This function is for fetch data from mysql table according to requirement for Bootgrid plugin. In this function we have make fetch data select query with Where clause for searching data, order_by clause for sorting data, and limit clause for pagination of data.


count_all_data() - This function return number of rows in employee table.


insert() - This mainly used for insert database operaton. It will make insert query, execute query and insert data into Database.


fetch_single_data() - This function is used for Select data of single employee based on value of $id variable.

update() - This function is for perform update or edit mysql database operation.

delete() - This function is for do mysql delete or remove data operation in Codeigniter.


application/models/Bootgrid_model.php


<?php
class Bootgrid_model extends CI_Model
{
 var $records_per_page = 10;
 var $start_from = 0;
 var $current_page_number = 1;

 function make_query()
 {
  if(isset($_POST["rowCount"]))
  {
   $this->records_per_page = $_POST["rowCount"];
  }
  else
  {
   $this->records_per_page = 10;
  }
  if(isset($_POST["current"]))
  {
   $this->current_page_number = $_POST["current"];
  }
  $this->start_from = ($this->current_page_number - 1) * $this->records_per_page;
  $this->db->select("*");
  $this->db->from("tbl_employee");
  if(!empty($_POST["searchPhrase"]))
  {
   $this->db->like('name', $_POST["searchPhrase"]);
   $this->db->or_like('address', $_POST["searchPhrase"]);
   $this->db->or_like('gender', $_POST["searchPhrase"]);
   $this->db->or_like('designation', $_POST["searchPhrase"]);
   $this->db->or_like('age', $_POST["searchPhrase"]);
  }
  if(isset($_POST["sort"]) && is_array($_POST["sort"]))
  {
   foreach($_POST["sort"] as $key => $value)
   {
    $this->db->order_by($key, $value);
   }
  }
  else
  {
   $this->db->order_by('id', 'DESC');
  }
  if($this->records_per_page != -1)
  {
   $this->db->limit($this->records_per_page, $this->start_from);
  }
  $query = $this->db->get();
  return $query->result_array();
 }

 function count_all_data()
 {
  $this->db->select("*");
  $this->db->from("tbl_employee");
  $query = $this->db->get();
  return $query->num_rows();
 }

 function insert($data)
 {
  $this->db->insert('tbl_employee', $data);
 }

 function fetch_single_data($id)
 {
  $this->db->where('id', $id);
  $query = $this->db->get('tbl_employee');
  return $query->result_array();
 }

 function update($data, $id)
 {
  $this->db->where('id', $id);
  $this->db->update('tbl_employee', $data);
 }

 function delete($id)
 {
  $this->db->where('id', $id);
  $this->db->delete('tbl_employee');
 }
}

?>


bootgrid.php(Views)


View file in Codeigniter framework is used for display HTML output on Web page. This bootgrid.php view file you can find under application/views folder. Here we have make HTML table as per Bootgrid plugin, and below you can find jQuery code, in which we have initialiaze jQuery Bootgrid plugin using bootgrid() method. Under this method we have trigger Ajax request for fetch data, and under this also we have make edit and delete button also under formatters option.



<html>
<head>
    <title>jQuery Bootgrid - Server Side Processing in Codeigniter</title>
    
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-bootgrid/1.3.1/jquery.bootgrid.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> 
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-bootgrid/1.3.1/jquery.bootgrid.js"></script>  
</head>
<body>
    <div class="container box">
        <h3 align="center">jQuery Bootgrid - Server Side Processing in Codeigniter</h3><br />
        <div class="panel panel-default">
            <div class="panel-heading">
                <div class="row">
                    <div class="col-md-10">
                        <h3 class="panel-title">Employee List</h3>
                    </div>
                    <div class="col-md-2" align="right">
                        <button type="button" id="add_button" data-toggle="modal" data-target="#employeeModal" class="btn btn-info btn-xs">Add</button>
                    </div>
                </div>
                
            </div>
            <div class="panel-body">
                <div class="table-responsive">
                    <table id="employee_data" class="table table-striped table-bordered">
                        <thead>
                            <tr>
                                <th data-column-id="name">Name</th>
                                <th data-column-id="address">Address</th>
                                <th data-column-id="gender">Gender</th>
                                <th data-column-id="designation">Designation</th>
                                <th data-column-id="age">Age</th>
                                <th data-column-id="commands" data-formatter="commands" data-sortable="false">Action</th>
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
       </div>
    </div>
</body>
</html>

<div id="employeeModal" class="modal fade">
    <div class="modal-dialog">
        <form method="post" id="employee_form">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Add Employee</h4>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label>Enter Name</label>
                        <input type="text" name="name" id="name" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label>Enter Address</label>
                        <textarea name="address" id="address" class="form-control"></textarea>
                    </div>
                    <div class="form-group">
                        <label>Select 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 Designation</label>
                        <input type="text" name="designation" id="designation" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label>Enter Age</label>
                        <input type="text" name="age" id="age" class="form-control" />
                    </div>
                </div>
                <div class="modal-footer">
                    <input type="hidden" name="employee_id" id="employee_id" />
                    <input type="hidden" name="operation" id="operation" value="Add" />
                    <input type="submit" name="action" id="action" class="btn btn-success" value="Add" />
                </div>
            </div>
        </form>
    </div>
</div>

<script type="text/javascript" language="javascript" >
$(document).ready(function(){
    
    var employeeTable = $('#employee_data').bootgrid({
        ajax:true,
        rowSelect: true,
        post:function()
        {
            return{
                id:"b0df282a-0d67-40e5-8558-c9e93b7befed"
            }
        },
        url:"<?php echo base_url(); ?>bootgrid/fetch_data",
        formatters:{
            "commands":function(column, row)
            {
                return "<button type='button' class='btn btn-warning btn-xs update' data-row-id='"+row.id+"'>Edit</button>" + "&nbsp; <button type='button' class='btn btn-danger btn-xs delete' data-row-id='"+row.id+"'>Delete</button>";
            }
        }
    });

    $('#add_button').click(function(){
        $('#employee_form')[0].reset();
        $('.modal-title').text("Add Employee");
        $('#action').val("Add");
        $('#operation').val("Add");
    });

    $(document).on('submit', '#employee_form', function(event){
        event.preventDefault();
        var name = $('#name').val();
        var address = $('#address').val();
        var gender = $('#gender').val();
        var designation = $('#designation').val();
        var age = $('#age').val();
        var form_data = $(this).serialize();
        if(name != '' && address != '' &&  gender != '' &&  designation != '' && age != '')
        {
            $.ajax({
                url:"<?php echo base_url(); ?>bootgrid/action",
                method:"POST",
                data:form_data,
                success:function(data)
                {
                    alert(data);
                    $('#employee_form')[0].reset();
                    $('#employeeModal').modal('hide');
                    $('#employee_data').bootgrid('reload');
                }
            });
        }
        else
        {
            alert("All Fields are Required");
        }
    });

    $(document).on("loaded.rs.jquery.bootgrid", function(){
        employeeTable.find('.update').on('click', function(event){
            var id = $(this).data('row-id');
            $.ajax({
                url:"<?php echo base_url(); ?>bootgrid/fetch_single_data",
                method:"POST",
                data:{id:id},
                dataType:"json",
                success:function(data)
                {
                    $('#employeeModal').modal('show');
                    $('#name').val(data.name);
                    $('#address').val(data.address);
                    $('#gender').val(data.gender);
                    $('#designation').val(data.designation);
                    $('#age').val(data.age);
                    $('.modal-title').text("Edit Employee Details");
                    $('#employee_id').val(id);
                    $('#action').val('Edit');
                    $('#operation').val('Edit');
                }
            });
        });

        employeeTable.find('.delete').on('click', function(event){
            if(confirm("Are you sure you want to delete this?"))
            {
                var id = $(this).data('row-id');
                $.ajax({
                    url:"<?php echo base_url(); ?>bootgrid/delete_data",
                    method:"POST",
                    data:{id:id},
                    success:function(data)
                    {
                        alert(data);
                        $('#employee_data').bootgrid('reload');
                    }
                });
            }
            else
            {
                return false;
            }
        });
    });
    
});
</script>


By using this post, you will make Codeigniter Ajax Single Page Application using jQeury Bootgrid plugin.

Friday, 21 December 2018

How to Load Dynamic Data in jQuery UI Tooltip using Ajax with PHP



If you are using jQuery as front-end for you web development, then this post will helpful. Because in this post we have covered topic like How to Load Ajax content in jQuery UI Tooltip plugin by using PHP script. Do you know what is tooltip, in a web development tooltip is a simple message that will fade in on web page when mouse cursor is move over any element like icon, image, hyperlink or simple text on webpage. But here we will load dynamic data into jQuery Tooltip by using PHP script with Ajax. By using Ajax, it will called request for fetch data from Mysql database, and convert into HTML format and load into tooltip plugin. That means all details will be appear on web page in tooltip while cursor move on particular element on web page.

By using Tooltip plugin, it will increase the UI of your web application. For make dynamic tooltip here we have use jQuery UI library tooltip plugin. By using tooltip, we can display hint or information of graphical UI. It is mainly initialize when cursor move hover on any element on web page. There many different ways we can use tooltips in web development, e.g. we can use tooltip for display for validation message on web page. There are different other way we can use tooltip. Tooltip is also benifit for form elements to display additional information for any HTML element in form.

Here we have take simple example of display student additional details in tooltip. When mouse move on any student name, in tooltip we have load that student image and other details like name phone number etc. For do this things we have use Ajax with jquery UI Tooltip plugin. For initialize tooltip plugin, here we have use tooltip() method. This method has been used to initialize tooltip plugin on HTML element. When mouse move on HTML element then here we have trigger Ajax request under content option callback function. This Ajax request send request to PHP script and fetch particular student data, convert into HTML format and lastly load under jQuery Tooltip plugin. For get complete source code of How to Load Dynamic Data in jQuery UI Tooltip using Ajax with PHP, below you can find complete source code.








Source Code


database_connection.php



<?php

//database_connection.php

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


?>


index.php



<!--
//index.php
!-->

<?php

include('database_connection.php');

$query = "SELECT * FROM tbl_student ORDER BY student_name ASC";

$statement = $connect->prepare($query);

$statement->execute();

$result = $statement->fetchAll();

?>

<html>  
    <head>  
        <title>How to Load Ajax Data in jQuery UI Tooltip using PHP</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    </head>  
    <body>  
        <div class="container">
   <br />
   
   <h3 align="center">How to Load Ajax Data in jQuery UI Tooltip using PHP</a></h3><br />
   <br />
   <div class="row">
    <div class="col-md-3">
    
    </div>
    <div class="col-md-6">
     <div class="panel panel-default">
      <div class="panel-heading">
       <h3 class="panel-title">Student Details</h3>
      </div>
      <div class="panel-body">
       <div class="table-responsive">
        <table class="table table-striped table-bordered">
         <tr>
          <th>Student Name</th>
         </tr>
         <?php
         foreach($result as $row)
         {
          echo '<tr><td><b><a href="#" id="'.$row["student_id"].'" title=" ">'.$row["student_name"].'</a></b></td></tr>';
         }
         ?>
        </table>
       </div>
      </div>
     </div>
    </div>
   </div>
  </div>
    </body>  
</html>  




<script>  
$(document).ready(function(){ 

 $('a').tooltip({
  classes:{
   "ui-tooltip":"highlight"
  },
  position:{ my:'left center', at:'right+50 center'},
  content:function(result){
   $.post('fetch.php', {
    id:$(this).attr('id')
   }, function(data){
    result(data);
   });
  }
 });
  
});  
</script>





fetch.php



<?php

//fetch.php

include('database_connection.php');

if(isset($_POST["id"]))
{
 $query = "SELECT * FROM tbl_student WHERE student_id = '".$_POST["id"]."'";

 $statement = $connect->prepare($query);

 $statement->execute();

 $result = $statement->fetchAll();

 $output = '';

 foreach($result as $row)
 {
  $output .= '
  <img src="images/'.$row["image"].'" class="img-thumbnail" />
  <h4>Name - '.$row["student_name"].'</h4>
  <h4>Phone No. - '.$row["student_phone"].'</h4>
  ';
 }
 echo $output;
}

?>

Wednesday, 19 December 2018

How to Create Editable Select Box using jQuery in PHP



Hi, Guys in this post you can learn how to convert simple select box or combo box into editable select box by using jQuery with PHP script. By using editable dropdown list box user can easily filter list of option from large number of option, and he can select required option which he want to select at the time of form filling. This is required because if in select box there are large number of option then at the time of form filling by user, it will difficult for user for find right option from list of option. If select box is editable then user can type something under dropdown list box, and he can filter option according what he has type. By filtering options user can get proper option which he has find from list of option.

For make editable dropdown list box here we have use jQuery Editable Select plugin which you can find here from this Github link. From this link you can download this jQuery Editable Select plugin, and here you can also find complete documentation of this plugin also. Here in this post we will discuss how to make dynamic editable dropdown listbox by using this jQuery plugin with PHP. In short how to use jQuery Editable Select plugin with PHP script. Editable select box will add one feature in you web application, because it has reduce the work of user for finding option, and it is also increase the appearance of your website UI also. It will increase the functionality of your web based application.

Now question is arise how can convert simple dropdown list box to Editable dropdown list box by using this plugin. It is very simple, you have to just include library of this plugin in your web page, and after this in you have to called editableSelect() method on Select box attribute like class or id. Once this method has been called then it will initialize this plugin and it will convert select box to editable select box. In this post we have step by step describute how to make editable select box by using jQuery plugin, And how to use this editable select box in actual form based application using PHP. Below you can find PHP Mysql Crud operation application in which we have used editable dropdown list box, and how to use this feature with real web based application.









Source Code


database_connection.php



<?php

//database_connection.php

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

?>


index.php



<?php

//index.php

include('database_connection.php');

$query = "SELECT * FROM apps_countries ORDER BY country_name ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();


?>

<html>  
    <head>  
        <title>How to Make Editable Select Box using jQuery with PHP</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <link rel="stylesheet" href="jquery-editable-select.min.css" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <script src="jquery-editable-select.min.js"></script>
  
    </head>  
    <body>  
        <div class="container">  
            <br />  
            <br />
   <br />
   <h2 align="center">How to Make Editable Select Box using jQuery with PHP</h2><br />
   <div class="row">
    <div class="col-md-3"></div>
    <div class="col-md-6">
     <form method="post" id="sample_form">
      <div class="form-group">
       <label>Enter Name</label>
       <input type="text" name="name" id="name" class="form-control">
      </div>
      <div class="form-group">
       <label>Select Country</label>
       <select name="country" id="country" class="form-control">
       <?php
       foreach($result as $row)
       {
        echo '<option value="'.$row["country_name"].'">'.$row["country_name"].'</option>';
       }
       ?>
       </select>
      </div>
      <div class="form-group">
       <input type="hidden" name="action" id="action" value="add" />
       <input type="hidden" name="hidden_id" id="hidden_id" value="" /> 
       <input type="submit" name="Save" id="save" class="btn btn-success" value="Save" />
      </div>
     </form>
     <br />
     <div class="table-responsive">
      <table class="table table-bordered">
       <thead>
        <tr>
         <th>Name</th>
         <th>Country</th>
         <th>Edit</th>
        </tr>
       </thead>
       <tbody>
        
       </tbody>
      </table>
     </div>
    </div>
    
   </div>
   
   
   <br />
   <br />
   <br />
  </div>
    </body>  
</html>  
<script>  
$(document).ready(function(){
 
 fetch_data();
 
 function fetch_data()
 {
  $.ajax({
   url:"fetch.php",
   method:"POST",
   success:function(data)
   {
    $('tbody').html(data);
   }
  });
 }
 
 $('#country').editableSelect();
 
 $('#sample_form').on('submit', function(event){
  event.preventDefault();
  
  if($('#name').val() == '')
  {
   alert("Enter Name");
   return false;
  }
  else if($('#country').val() == '')
  {
   alert("Select Country");
   return false;
  }
  else
  {
   $.ajax({
    url:"action.php",
    method:"POST",
    data:$(this).serialize(),
    success:function(data)
    {
     alert(data);
     $('#sample_form')[0].reset();
     $('#action').val("add");
     $('#save').val('Save');
     fetch_data();
    }
   });
  }
 });
 
 $(document).on('click', '.edit', function(){
  var id = $(this).attr("id");
  var action = 'fetch_single';
  $.ajax({
   url:"action.php",
   method:"POST",
   data:{id:id, action:action},
   dataType:'json',
   success:function(data)
   {
    $('#hidden_id').val(id);
    $('#name').val(data.name);
    $('#country').val(data.country);
    $('#action').val("edit");
    $('#save').val('Edit');
   }
  });
 });

});  
</script>




fetch.php



<?php

//fetch.php

include('database_connection.php');

$query = "SELECT * FROM sample_data ORDER BY id DESC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$total_row = $statement->rowCount();
$output = '';
if($total_row > 0)
{
 foreach($result as $row)
 {
  $output .= '
  <tr>
   <td>'.$row["name"].'</td>
   <td>'.$row["country"].'</td>
   <td><button type="button" name="edit" class="btn btn-primary btn-xs edit" id="'.$row["id"].'">Edit</button></td>
  </tr>
  ';
 }
}
else
{
 $output .= '
 <tr>
  <td colspan="3" align="center">Data not found</td>
 </tr>
 ';
}

echo $output;

?>


action.php



<?php

//action.php

include('database_connection.php');

if(isset($_POST["action"]))
{ 
 
 if($_POST["action"] == "add")
 {
  $data = array(
   ':name'  => $_POST["name"],
   ':country'  => $_POST["country"]
  );
  
  $query = "
  INSERT INTO sample_data (name, country) 
  VALUES (:name, :country)
  ";
  
  $statement = $connect->prepare($query);
  if($statement->execute($data))
  {
   echo 'Data Inserted';
  }
 }
 
 if($_POST["action"] == 'fetch_single')
 {
  $query = "SELECT * FROM sample_data WHERE id='".$_POST["id"]."'";
  $statement = $connect->prepare($query);
  $statement->execute();
  $result = $statement->fetchAll();
  foreach($result as $row)
  {
   $output['name'] = $row["name"];
   $output['country'] = $row["country"];
  }
  echo json_encode($output);
 }
 
 if($_POST["action"] == "edit")
 {
  $data = array(
   ':name'  => $_POST["name"],
   ':country'  => $_POST["country"],
   ':id'  => $_POST["hidden_id"]
  );
  $query = "
  UPDATE sample_data 
  SET name = :name, country = :country 
  WHERE id = :id
  ";
  $statement = $connect->prepare($query);
  if($statement->execute($data))
  {
   echo 'Data Updated';
  }
 }
 
}

?>





Thursday, 13 December 2018

Live Table Add Edit Delete in Laravel using Ajax jQuery

Live Table Add Edit Delete in Laravel using Ajax jQuery - 1




Live Table Add Edit Delete in Laravel using Ajax jQuery - 2




Live Table Add Edit Delete in Laravel using Ajax jQuery - 3




Live Table Add Edit Delete in Laravel using Ajax jQuery - 4





If you are looking for web tutorial on how to make live table application in Laravel framework by using Ajax and jQuery. So, you are come on right place, here you can find step by step by not only web tutorial but also video tutorial on Live table Insert Update Delete mysql table records in Laravel framework with Ajax and jQuery. We all know Laravel is a robust PHP framework for develop enterprise level application from scratch with write small PHP code and reuse same code. If we have use Ajax jQuery with Laravel, then it will make standard level web application.

In this post we have make Single page Live table or Inline table application in Laravel by using Ajax jQuery. In this application we will perform all CRUD operation like Create, Read, Update and Delete mysql database data from Laravel Live table or Inline table application. In this application use can Create or Add or Insert new data into mysql table from table, User can Update or edit exisiting records of Mysql table from this Laravel Live table. User can delete or remove mysql data from this Application. He can perform all this operation without going to other page, but from single html table he can perform all CRUD operation. That means here we will make Single page Live table crud application in Laravel using Ajax and jQuery.

Most of the application there main function is insert, update, delete and read mysql data. So, here we have make Single page Inline table application in Laravel with Ajax jquery, and perform all function from single page without refresh of web page. So, it will increase the speed of your web application, and it will also advance feature in your application. It will improve your application efficiency also. So, if Laravel framework will work with Ajax and jQuery, then it will increase your web presense user interface from user also. Below you can find step by step source code of Live table insert update delete mysql data using Ajax jQuery in Laravel framework.






Source Code


First we have to create Livetable controller, for this we have to go command prompt, and write following command, this command will create LiveTable.php controller file under app/HTTP/controllers folder.


php artisan make:controller LiveTable


Livetable.php


Once controller has been created under app/HTTP/controllers folder. In this class you can find following method for handle HTTP request of Live table crud operation in Laravel.

index() - This is the root method of this class, it will load live_table.blade.php view file in browser, once this live table controller has been called in browser.

fetch_data() - This method has receieved ajax request for fetch data from live_table.blade.php file, and this function return data in json format.

add_data() - This method has received ajax request for insert or add new records in mysql table from live_table.blade.php file, and this method return response once data has been successfully inserted.

update_data() - This method is used for update or edit mysql table records using Ajax. Ajax request has been send from view file to this method for edit or update existing of data of Mysql in Laravel using Ajax.

delete_data() - This method has received delete mysql table data request from Ajax, This method mainly used for delete or remove data operation in Laravel. Once this method has delete data then it send back response to Ajax request.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class LiveTable extends Controller
{
    function index()
    {
        return view('live_table');
    }

    function fetch_data(Request $request)
    {
        if($request->ajax())
        {
            $data = DB::table('tbl_sample')->orderBy('id','desc')->get();
            echo json_encode($data);
        }
    }

    function add_data(Request $request)
    {
        if($request->ajax())
        {
            $data = array(
                'first_name'    =>  $request->first_name,
                'last_name'     =>  $request->last_name
            );
            $id = DB::table('tbl_sample')->insert($data);
            if($id > 0)
            {
                echo '<div class="alert alert-success">Data Inserted</div>';
            }
        } 
    }

    function update_data(Request $request)
    {
        if($request->ajax())
        {
            $data = array(
                $request->column_name       =>  $request->column_value
            );
            DB::table('tbl_sample')
                ->where('id', $request->id)
                ->update($data);
            echo '<div class="alert alert-success">Data Updated</div>';
        }
    }

    function delete_data(Request $request)
    {
        if($request->ajax())
        {
            DB::table('tbl_sample')
                ->where('id', $request->id)
                ->delete();
            echo '<div class="alert alert-success">Data Deleted</div>';
        }
    }
}
?>





livetable.blade.php


This is view file of Live table application in Laravel and this file you can find under resources/view/livetable.blade.php. This file is used for display output on browser. In this view file you can find html, jquery and Ajax source code for fetch and insert data into mysql table in Laravel. For fetch data using Ajax, here we have make fetch_data() jQuery function which send Ajax request to LiveTable.php controller. For Insert, Update and delete mysql data using Ajax also, here you can find jQuery code in which Ajax request has been send to LiveTable.php controller class.


<!DOCTYPE html>
<html>
 <head>
  <title>Live Table Insert Update Delete in Laravel using Ajax jQuery</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container box">
   <h3 align="center">Live Table Insert Update Delete in Laravel using Ajax jQuery</h3><br />
   <div class="panel panel-default">
    <div class="panel-heading">Sample Data</div>
    <div class="panel-body">
     <div id="message"></div>
     <div class="table-responsive">
      <table class="table table-striped table-bordered">
       <thead>
        <tr>
         <th>First Name</th>
         <th>Last Name</th>
         <th>Delete</th>
        </tr>
       </thead>
       <tbody>
       
       </tbody>
      </table>
      {{ csrf_field() }}
     </div>
    </div>
   </div>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){

 fetch_data();

 function fetch_data()
 {
  $.ajax({
   url:"/livetable/fetch_data",
   dataType:"json",
   success:function(data)
   {
    var html = '';
    html += '<tr>';
    html += '<td contenteditable id="first_name"></td>';
    html += '<td contenteditable id="last_name"></td>';
    html += '<td><button type="button" class="btn btn-success btn-xs" id="add">Add</button></td></tr>';
    for(var count=0; count < data.length; count++)
    {
     html +='<tr>';
     html +='<td contenteditable class="column_name" data-column_name="first_name" data-id="'+data[count].id+'">'+data[count].first_name+'</td>';
     html += '<td contenteditable class="column_name" data-column_name="last_name" data-id="'+data[count].id+'">'+data[count].last_name+'</td>';
     html += '<td><button type="button" class="btn btn-danger btn-xs delete" id="'+data[count].id+'">Delete</button></td></tr>';
    }
    $('tbody').html(html);
   }
  });
 }

 var _token = $('input[name="_token"]').val();

 $(document).on('click', '#add', function(){
  var first_name = $('#first_name').text();
  var last_name = $('#last_name').text();
  if(first_name != '' && last_name != '')
  {
   $.ajax({
    url:"{{ route('livetable.add_data') }}",
    method:"POST",
    data:{first_name:first_name, last_name:last_name, _token:_token},
    success:function(data)
    {
     $('#message').html(data);
     fetch_data();
    }
   });
  }
  else
  {
   $('#message').html("<div class='alert alert-danger'>Both Fields are required</div>");
  }
 });

 $(document).on('blur', '.column_name', function(){
  var column_name = $(this).data("column_name");
  var column_value = $(this).text();
  var id = $(this).data("id");
  
  if(column_value != '')
  {
   $.ajax({
    url:"{{ route('livetable.update_data') }}",
    method:"POST",
    data:{column_name:column_name, column_value:column_value, id:id, _token:_token},
    success:function(data)
    {
     $('#message').html(data);
    }
   })
  }
  else
  {
   $('#message').html("<div class='alert alert-danger'>Enter some value</div>");
  }
 });

 $(document).on('click', '.delete', function(){
  var id = $(this).attr("id");
  if(confirm("Are you sure you want to delete this records?"))
  {
   $.ajax({
    url:"{{ route('livetable.delete_data') }}",
    method:"POST",
    data:{id:id, _token:_token},
    success:function(data)
    {
     $('#message').html(data);
     fetch_data();
    }
   });
  }
 });


});
</script>


web.php


Once you have completed working on Controller class code and view file code, lastly you have to set route for LiveTable.php controller class. In this class we have create index(), fetch_data(), add_data(), update_data() and delete_data() method for fetch, insert and update data using Ajax in Laravel. For set route in Laravel, we have to go to routes/web.php file. And in this file we have to write following code for set route.


Route::get('/livetable', 'LiveTable@index');
Route::get('/livetable/fetch_data', 'LiveTable@fetch_data');
Route::post('/livetable/add_data', 'LiveTable@add_data')->name('livetable.add_data');
Route::post('/livetable/update_data', 'LiveTable@update_data')->name('livetable.update_data');
Route::post('/livetable/delete_data', 'LiveTable@delete_data')->name('livetable.delete_data');


Lastly for run Laravel Live table add edit delete mysql data application using Ajax jQuery, we have to go to command prompt, and write following command.


php artisan serve


Once this command has been run under command prompt in which you have already run composer command, then you will provide you this http://127.0.0.1:8000 link, and just run following link for run Live table application.


http://127.0.0.1:8000/livetable



Friday, 7 December 2018

How to Create Entire Div Clickable using jQuery



In this post you can find the solution of How to make whole Div tag clickable by using jQuery. There are many ways we can make Div tag clickable like by using CSS, HTML or javascript. But here we will seen how can use simple jQuery code to create whole Div clickable. In web development there are many places in which we have to put link on whole div tag not only single text. Then at that time we have put simple javascript in onclick attribute of div tag and make whole div tag clickable. Or by using CSS we have convert simple div tag to clickable div tag.

But by this method it has affect SEO score of our web page, because in html code we have add more attribute. But if we have use simple jQuery for this things then in single line of code it will convert div tag to clickable div tag without adding any extra tag in our html code. This source you can also implement other tag like span tag, html 5 article tag or any other tag which we can use in place of Div. So, by this code we not only convert Div tag to clickable tag, but also we can aslo use same code for convert other tag to clickable tag. Below you can find source code and online demo of How to make whole Div clickable by using jQuery.







Source Code



<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>How to make Whole Div Clickable using jquery</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 <style>
 .clickable
 {
  border:1px solid #ccc;
  cursor:pointer;
  padding-top:12px;
  padding-bottom:12px;
 }
 </style>
</head>
<body>
 <div class="container">
  <br />
  <h3 align="center">How to make Whole Div Clickable using jquery</h3>
  <br />
  
  <div class="row">
   <div class="col-md-4"></div>
   <div class="col-md-4 clickable">
    <img src="image.jpg" class="img-thumbnail" />
    <h3>Exporting Data into Multiple Excel sheets in PHP</h3>
    <p>If you are working with large amount of data and mainly we have use Excel and CSV file format for export data in web development. So, in this post we have describe how to split huge amount of mysql datable data and export into multiple excel or csv file by using PHPExcel library in PHP.</p>
    <a href="https://www.webslesson.info/2018/12/exporting-data-into-multiple-excel-sheets-in-php.html">Read more</a>
   </div>
   <div class="col-md-4"></div>
  </div>
  
 </div>
</body>
</html>
<script>
$(document).ready(function(){
 
 $('.clickable').click(function(){
  window.location = $(this).find("a").attr("href");
 });
 
});
</script>