Monday, 16 September 2019

Add or Remove Dynamic Dependent Select Box using jQuery with PHP Ajax

Part - 1




Part - 2




Part - 3




This is one more post on Add or Remove Input field, but now here we will discuss, how to Add or Remove Dynamic Dependent Select Box input field by using jQuery and How to insert Multiple input field data into Mysql table by using PHP with Ajax. Dynamic Dependent Select box or Drop down list box means child select box data must be depend on the value of select in parent select box. When we have change the value of parent select box then child select box data will be automatically change.

In some of our previous tutorial, we have already discuss how to Add or remove text box input field using jQuery with Ajax and PHP and we have also seen how to add or remove dynamic select box input field data using jQuery Ajax and PHP. But now question arise how to insert multiple form data with field like dynamic dependent select box. For this type of data we have to use add or remove input field using jQuery.

Currently, we have seen in PHP web development, in many event in which we want to insert multiple data into mysql database. Then at that time we would to require add or remove input fields concept. This feature has been used mainly used for multiple data insert into mysql table. But suppose in multiple data, we want to process dynamic dependent select box data, then at that time one question arise can we solve the problem of processing of multiple dynamic dependent select box data with add or remove input field concept. Below you can find complete source code for add or remove dynamic dependent select box using jquery and insert multiple input fields data using ajax with php.









Source Code


Mysql Table Stucture



--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_category`
--

CREATE TABLE `tbl_category` (
  `category_id` int(11) NOT NULL,
  `category_name` varchar(200) NOT NULL,
  `parent_category_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_category`
--

INSERT INTO `tbl_category` (`category_id`, `category_name`, `parent_category_id`) VALUES
(2, 'Chemicals', 0),
(3, 'Inorganic chemicals', 2),
(4, 'Organic Chemicals', 2),
(5, 'Electronics', 0),
(6, 'Laptop', 5),
(7, 'Dell', 6),
(8, 'i3 Processor', 7),
(9, 'i5 Processors', 7),
(10, 'i7 Processors', 7),
(11, 'Epoxy', 2),
(12, 'Fine Chemicals', 2),
(13, 'Mobile', 5),
(14, 'Sensors', 5),
(15, 'Food', 0),
(16, 'Textile', 0),
(17, 'Fruits', 15),
(18, 'Vegetables', 15),
(19, 'Safety Shoes', 16),
(20, 'Uniform', 16);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_category`
--
ALTER TABLE `tbl_category`
  ADD PRIMARY KEY (`category_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_category`
--
ALTER TABLE `tbl_category`
  MODIFY `category_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=21;

-------

--
-- Table structure for table `items`
--

CREATE TABLE `items` (
  `item_id` int(11) NOT NULL,
  `item_name` varchar(250) NOT NULL,
  `item_category_id` int(11) NOT NULL,
  `item_sub_category_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for table `items`
--
ALTER TABLE `items`
  ADD PRIMARY KEY (`item_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `items`
--
ALTER TABLE `items`
  MODIFY `item_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;


database_connection.php



<?php

//database_connection.php

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

function fill_select_box($connect, $category_id)
{
 $query = "
  SELECT * FROM tbl_category 
  WHERE parent_category_id = '".$category_id."'
 ";

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

 $statement->execute();

 $result = $statement->fetchAll();

 $output = '';

 foreach($result as $row)
 {
  $output .= '<option value="'.$row["category_id"].'">'.$row["category_name"].'</option>';
 }

 return $output;
}

?>


index.php



<?php

//index.php

include('database_connection.php');

?>

<!DOCTYPE html>
<html>
  <head>
    <title>Add Remove Dynamic Dependent Select Box using Ajax jQuery with PHP</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  </head>
  <body>
    <br />
    <div class="container">
      <h3 align="center">Add Remove Dynamic Dependent Select Box using Ajax jQuery with PHP</h3>
      <br />
      <h4 align="center">Enter Item Details</h4>
      <br />
      <form method="post" id="insert_form">
        <div class="table-repsonsive">
          <span id="error"></span>
          <table class="table table-bordered" id="item_table">
            <thead>
              <tr>
                <th>Enter Item Name</th>
                <th>Category</th>
                <th>Sub Category</th>
                <th><button type="button" name="add" class="btn btn-success btn-xs add"><span class="glyphicon glyphicon-plus"></span></button></th>
              </tr>
            </thead>
            <tbody></tbody>
          </table>
          <div align="center">
            <input type="submit" name="submit" class="btn btn-info" value="Insert" />
          </div>
        </div>
      </form>
    </div>
  </body>
</html>
<script>
    $(document).ready(function(){
      
      var count = 0;

      $(document).on('click', '.add', function(){
        count++;
        var html = '';
        html += '<tr>';
        html += '<td><input type="text" name="item_name[]" class="form-control item_name" /></td>';
        html += '<td><select name="item_category[]" class="form-control item_category" data-sub_category_id="'+count+'"><option value="">Select Category</option><?php echo fill_select_box($connect, "0"); ?></select></td>';
        html += '<td><select name="item_sub_category[]" class="form-control item_sub_category" id="item_sub_category'+count+'"><option value="">Select Sub Category</option></select></td>';
        html += '<td><button type="button" name="remove" class="btn btn-danger btn-xs remove"><span class="glyphicon glyphicon-minus"></span></button></td>';
        $('tbody').append(html);
      });

      $(document).on('click', '.remove', function(){
        $(this).closest('tr').remove();
      });

      $(document).on('change', '.item_category', function(){
        var category_id = $(this).val();
        var sub_category_id = $(this).data('sub_category_id');
        $.ajax({
          url:"fill_sub_category.php",
          method:"POST",
          data:{category_id:category_id},
          success:function(data)
          {
            var html = '<option value="">Select Sub Category</option>';
            html += data;
            $('#item_sub_category'+sub_category_id).html(html);
          }
        })
      });

      $('#insert_form').on('submit', function(event){
        event.preventDefault();
        var error = '';
        $('.item_name').each(function(){
          var count = 1;
          if($(this).val() == '')
          {
            error += '<p>Enter Item name at '+count+' Row</p>';
            return false;
          }
          count = count + 1;
        });

        $('.item_category').each(function(){
          var count = 1;

          if($(this).val() == '')
          {
            error += '<p>Select Item Category at '+count+' row</p>';
            return false;
          }

          count = count + 1;

        });

        $('.item_sub_category').each(function(){

          var count = 1;

          if($(this).val() == '')
          {
            error += '<p>Select Item Sub category '+count+' Row</p> ';
            return false;
          }

          count = count + 1;

        });

        var form_data = $(this).serialize();

        if(error == '')
        {
          $.ajax({
            url:"insert.php",
            method:"POST",
            data:form_data,
            success:function(data)
            {
              if(data == 'ok')
              {
                $('#item_table').find('tr:gt(0)').remove();
                $('#error').html('<div class="alert alert-success">Item Details Saved</div>');
              }
            }
          });
        }
        else
        {
          $('#error').html('<div class="alert alert-danger">'+error+'</div>');
        }

      });
      
    });
</script>


fill_sub_category.php



<?php

//fill_sub_category.php

include('database_connection.php');

echo fill_select_box($connect, $_POST["category_id"]);

?>


insert.php



<?php

//insert.php;

if(isset($_POST["item_name"]))
{
 include('database_connection.php');

 for($count = 0; $count < count($_POST["item_name"]); $count++)
 {
  $data = array(
   ':item_name'   => $_POST["item_name"][$count],
   ':item_category_id'  => $_POST["item_category"][$count],
   ':item_sub_category_id' => $_POST["item_sub_category"][$count]
  );

  $query = "
   INSERT INTO items 
       (item_name, item_category_id, item_sub_category_id) 
       VALUES (:item_name, :item_category_id, :item_sub_category_id)
  ";

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

  $statement->execute($data);
 }

 echo 'ok';
}


?>



Wednesday, 11 September 2019

PHP Form with Google reCaptcha



If you not know how to add Google reCaptcha in PHP form, then you have come on right place. Because in this post you can find solution of How to integrate Google reCaptcha in PHP form and here you can also find how to validate PHP form with Google reCaptcha by using Ajax jQuery.

Form data has been validate with Google reCaptcha is required because we all know spamming is one of very common problem which has been faced on web. Every Website owner prevent their website from invalid spam traffic or spam comment.

Before programmer has used random captcha code for prevent spamming or bots filled in their website form. But this is old method and now most of the web application has been used Google reCAPTCHA, for verify that form input field has been filled by any human. Google reCAPTCHA is very simple to verify that he is user. User can verify just in single click for that they are not a robot.

Below you can find step by step guide for How to build PHP spam free form by using Google reCaptcha.



Step 1: Get Google reCaptcha API Key


For get Google reCaptcha API key, you first have Google account. If you have google account, then login into your Google account and visit this website https://www.google.com/recaptcha/admin.





Once you have visit above link then, you can see above image web page. Here you have to define label name, domain name in which you want to integrate Google reCaptcha and click on submit button. Here we want to use in localhost also so we have include localhost in domain list also. And lastly click on submit button, then you can get API key, which you can see below.









Add Google reCaptcha API key in your web page


In this tutorial, we will create our HTML form in index.php file. So, in this file first we need to add reCAPTCHA javascript library in our HTML code.


<script src="https://www.google.com/recaptcha/api.js" async defer></script>


After this we want to add following HTML code for generate Google reCAPTCHA widget in form.


<div class="g-recaptcha" data-sitekey="6Ldv2bcUAAAAAFeYuQAQWH7I_BVv2_2_fedg2Fpp"></div>


Here in data-sitekey value, we have to add site key which we have get from Google reCAPTCHA api key. Once you have add this code and refresh web page then Google reCaptcha widget will be created in your web page. Below you can source code of index.php file




index.php

<html>  
    <head>  
        <title>How to Implement Google reCaptcha in PHP Form</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>
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
    </head>  
    <body>  
        <div class="container" style="width: 600px">
   <br />
   
   <h3 align="center">How to Implement Google reCaptcha in PHP Form</a></h3><br />
   <br />
   <div class="panel panel-default">
      <div class="panel-heading">Register Form</div>
    <div class="panel-body">
     
     <form metod="post" id="captcha_form">
      <div class="form-group">
       <div class="row">
        <div class="col-md-6">
         <label>First Name <span class="text-danger">*</span></label>
         <input type="text" name="first_name" id="first_name" class="form-control" />
         <span id="first_name_error" class="text-danger"></span>
        </div>
        <div class="col-md-6">
         <label>Last Name <span class="text-danger">*</span></label>
         <input type="text" name="last_name" id="last_name" class="form-control" />
         <span id="last_name_error" class="text-danger"></span>
        </div>
       </div>
      </div>
      <div class="form-group">
       <label>Email Address <span class="text-danger">*</span></label>
       <input type="text" name="email" id="email" class="form-control" />
       <span id="email_error" class="text-danger"></span>
      </div>
      <div class="form-group">
       <label>Password <span class="text-danger">*</span></label>
       <input type="password" name="password" id="password" class="form-control" />
       <span id="password_error" class="text-danger"></span>
      </div>
      <div class="form-group">
       <div class="g-recaptcha" data-sitekey="6Ldv2bcUAAAAAFeYuQAQWH7I_BVv2_2_vvmn2Fpp"></div>
       <span id="captcha_error" class="text-danger"></span>
      </div>
      <div class="form-group">
       <input type="submit" name="register" id="register" class="btn btn-info" value="Register" />
      </div>
     </form>
     
    </div>
   </div>
  </div>
    </body>  
</html>

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

 $('#captcha_form').on('submit', function(event){
  event.preventDefault();
  $.ajax({
   url:"process_data.php",
   method:"POST",
   data:$(this).serialize(),
   dataType:"json",
   beforeSend:function()
   {
    $('#register').attr('disabled','disabled');
   },
   success:function(data)
   {
    $('#register').attr('disabled', false);
    if(data.success)
    {
     $('#captcha_form')[0].reset();
     $('#first_name_error').text('');
     $('#last_name_error').text('');
     $('#email_error').text('');
     $('#password_error').text('');
     $('#captcha_error').text('');
     grecaptcha.reset();
     alert('Form Successfully validated');
    }
    else
    {
     $('#first_name_error').text(data.first_name_error);
     $('#last_name_error').text(data.last_name_error);
     $('#email_error').text(data.email_error);
     $('#password_error').text(data.password_error);
     $('#captcha_error').text(data.captcha_error);
    }
   }
  })
 });

});
</script>


Validate User Response at Server side


After this we need to validate user response at server side, for this we have to process_data.php file, in which recaptcha response data will be received using Ajax. When user submit form, then reCAPTCHA widget response has been received at process_data.php using Ajax. Here we need to verify response by following php script.


if(empty($_POST['g-recaptcha-response']))
 {
  $captcha_error = 'Captcha is required';
 }
 else
 {
  $secret_key = '6Ldv2bcUAAAAAFXUKdLW_qljFd9FpxNguf06DHhp';

  $response = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret_key.'&response='.$_POST['g-recaptcha-response']);

  $response_data = json_decode($response);

  if(!$response_data->success)
  {
   $captcha_error = 'Captcha verification failed';
  }
 }


Here in secret key variable, we need to define secret key which we have get from Google reCaptcha website. Here you need to define your secret key which you have get at the time of generating Google reCAPTCHA API key.

For validate user response here we have send request to Google reCaptcha API url for check user response is proper or not using file_get_contents() function. Below you can find complete PHP script for validate form data with Google recaptcha response also.

process_data.php


<?php

//process_data.php

if(isset($_POST["first_name"]))
{
 $first_name = '';
 $last_name = '';
 $email = '';
 $password = '';

 $first_name_error = '';
 $last_name_error = '';
 $email_error = '';
 $password_error = '';
 $captcha_error = '';

 if(empty($_POST["first_name"]))
 {
  $first_name_error = 'First name is required';
 }
 else
 {
  $first_name = $_POST["first_name"];
 }

 if(empty($_POST["last_name"]))
 {
  $last_name_error = 'Last name is required';
 }
 else
 {
  $last_name = $_POST["last_name"];
 }
 if(empty($_POST["email"]))
 {
  $email_error = 'Email is required';
 }
 else
 {
  if(!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL))
  {
   $email_error = 'Invalid Email';
  }
  else
  {
   $email = $_POST["email"];
  }
 }

 if(empty($_POST["password"]))
 {
  $password_error = 'Password is required';
 }
 else
 {
  $password = $_POST["password"];
 }

 if(empty($_POST['g-recaptcha-response']))
 {
  $captcha_error = 'Captcha is required';
 }
 else
 {
  $secret_key = '6Ldv2bcUAAAAAFXUKdLW_qljFd9FpxNguf06DHhp';

  $response = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret_key.'&response='.$_POST['g-recaptcha-response']);

  $response_data = json_decode($response);

  if(!$response_data->success)
  {
   $captcha_error = 'Captcha verification failed';
  }
 }

 if($first_name_error == '' && $last_name_error == '' && $email_error == '' && $password_error == '' && $captcha_error == '')
 {
  $data = array(
   'success'  => true
  );
 }
 else
 {
  $data = array(
   'first_name_error' => $first_name_error,
   'last_name_error' => $last_name_error,
   'email_error'  => $email_error,
   'password_error' => $password_error,
   'captcha_error'  => $captcha_error
  );
 }

 echo json_encode($data);
}

?>


So, this was the complete step by step process for using Google reCaptcha with PHP and validate response using Ajax with PHP. We hope you can understan how to integrate Google reCAPTCHA checkbox using PHP.

Saturday, 7 September 2019

Make Captcha Script in PHP with Ajax



This post will explain you, how to make your own custom captcha in PHP using jQuery and Ajax in HTML form.

Do you know what is captcha. In web development, Captcha is one random generated alpha numeric captcha string, and it is stored in session variable for validate it with the captcha code enter by the user at the time of filling of form field.

Captacha is for prevent the bot or spammer for filling form field automatically. Because Captcha code has been display in an image, which can be only human can able to read it.

When we have allow public user to enter data into our website, then we need to identify that data has been enter by human. Because currently, many people has use robots to fill form data, so many unwanted data has been entered into website. So it will increase lots of load on our website, which will be down for sometime.

So, Captcha is one type of methods which helps website owner to prevent robots or bots from inserting of data. There are different type of Captcha like text-based, audio based or image based we can implement our web page, and it will generate random code dynamically. In form filling captcha code will be mandatory, without filling code user cannot submit form, so robot cannot read image text and robot will not submit form with data.

In this post, we will use PHP script for image with dynamic alpha numeric string and make graphics based captcha code. Here Captcha code will be stored under PHP $_SESSION variable for future use.And for validate user has enter correct captcha code, for this we will use jQuery and Ajax.







Source Code


index.php



<?php

//index.php

?>

<html>  
    <head>  
        <title>How to implement Custom Captcha Code in PHP</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" style="width: 600px">
   <br />
   
   <h3 align="center">How to implement Custom Captcha Code in PHP</a></h3><br />
   <br />
   <div class="panel panel-default">
      <div class="panel-heading">Register Form</div>
    <div class="panel-body">
     <form method="post" id="captch_form">
      <div class="form-group">
       <div class="row">
        <div class="col-md-6">
         <label>First Name</label>
         <input type="text" name="first_name" id="first_name" class="form-control" />
        </div>
        <div class="col-md-6">
         <label>Last Name</label>
         <input type="text" name="last_name" id="last_name" class="form-control" />
        </div>
       </div>
      </div>
      <div class="form-group">
       <label>Email Address</label>
       <input type="text" name="email" id="email" class="form-control" />
      </div>
      <div class="form-group">
       <label>Password</label>
       <input type="password" name="password" id="password" class="form-control" />
      </div>
      <div class="form-group">
       <div class="form-group">
                          <label>Code</label>
                          <div class="input-group">
                           <input type="text" name="captcha_code" id="captcha_code" class="form-control" />
                           <span class="input-group-addon" style="padding:0">
          <img src="image.php" id="captcha_image" />
         </span>
                          </div>
                         </div>
      </div>
      <div class="form-group">
       <input type="submit" name="register" id="register" class="btn btn-info" value="Register" />
      </div>
     </form>
    </div>
   </div>
  </div>
    </body>  
</html>



<script>
 $(document).ready(function(){
  
  $('#captch_form').on('submit', function(event){
   event.preventDefault();
   if($('#captcha_code').val() == '')
   {
    alert('Enter Captcha Code');
    $('#register').attr('disabled', 'disabled');
    return false;
   }
   else
   {
    alert('Form has been validate with Captcha Code');
    $('#captch_form')[0].reset();
    $('#captcha_image').attr('src', 'image.php');
   }
  });

  $('#captcha_code').on('blur', function(){
   var code = $('#captcha_code').val();
   
   if(code == '')
   {
    alert('Enter Captcha Code');
    $('#register').attr('disabled', 'disabled');
   }
   else
   {
    $.ajax({
     url:"check_code.php",
     method:"POST",
     data:{code:code},
     success:function(data)
     {
      if(data == 'success')
      {
       $('#register').attr('disabled', false);
      }
      else
      {
       $('#register').attr('disabled', 'disabled');
       alert('Invalid Code');
      }
     }
    });
   }
  });

 });
</script>



image.php



<?php

//image.php

session_start();

$random_alpha = md5(rand());

$captcha_code = substr($random_alpha, 0, 6);

$_SESSION['captcha_code'] = $captcha_code;

header('Content-Type: image/png');

$image = imagecreatetruecolor(200, 38);

$background_color = imagecolorallocate($image, 231, 100, 18);

$text_color = imagecolorallocate($image, 255, 255, 255);

imagefilledrectangle($image, 0, 0, 200, 38, $background_color);

$font = dirname(__FILE__) . '/arial.ttf';

imagettftext($image, 20, 0, 60, 28, $text_color, $font, $captcha_code);

imagepng($image);

imagedestroy($image);

?>


check_code.php



<?php

//check_code.php

session_start();

$code = $_POST['code'];

if($code == $_SESSION['captcha_code'])
{
 echo 'success';
}

?>


Tuesday, 3 September 2019

How to Upload and Resize Image in Laravel 5.8



If you are looking for tutorial on Resize Image before upload in Laravel 5.8 framework. So, you have come on the right place, because in this Laravel 5.8 image upload tutorial, in which we have step by step describe how to resize image in Laravel 5.8 framework at the time of uploading image. In Laravel 5.8 framework for resize image here we will use Intervention Image package for resize image at the time of uploading of an Image.

Resize image is very useful feature in any web based application, suppose in your web application if you have profile module and in this module you want to display profile image, then if you have display full size image then it will require more bandwidth for load image, but if you have load small thumbnail type image, then it will load fast. You can generate thumbnail image at the time of uploading of image by resize or cropping of image, you can generate thumbnail image and store in folder.

There are lots reader of our tutorial has requested us to publish web tutorial on how to resize image in Laravel 5.8 application. In Web development image resize is a required feature for use image as per size of the web page container. By Image resize it will help us to improve our loading of web page speed. In this post, we have decided to show how can we resize image in Laravel 5.8 by using intervention image library. By using this Intervention Library, we can easy to resize image at the time of uploading. Because this library has use PHP GD library and Imagegick for image resize and crop. Below you can find process for Resize image in Laravel 5.8.

  • Download and Install Laravel 5.8 framework
  • Download and Install Intervention Image Library
  • Make Controller in Laravel 5.8
  • Make View Blade File in Laravel 5.8
  • Set Route in Laravel 5.8
  • Run Laravel 5.8 Application


Download and Install Laravel 5.8 framework


For make application in Laravel 5.8 framework, first we need to download Laravel 5.8 framework and install in our local computer. For this we have go command prompt, in which first we need to run "composer" command, and go to directory in which we want to download and install laravel 5.8 framework. After this run following command.


composer create-project --prefer-dist laravel/laravel image_resize


This command will make image_resize folder in define directory, and in this folder it will download laravel 5.8 framework.

Download and Install Intervention Image Library


For resize image in Laravel 5.8 framework. For this here we have use Intervention Image package. Now we want download and install in Laravel 5.8 framework. For this we have to write following command, this command will download Intervention Image package in Laravel 5.8 framework for resize image at the time of uploading of image.



Make Controller in Laravel 5.8


In Laravel 5.8 application, for handle http request here we have to make controller. For make controller in Laravel 5.8 framework, first we need the system in which composer has been installed and then after go to your project root directory and run following command.


php artisan make:controller ResizeController


This command will make ResizeController.php controller class file in app/Http/Controllers folder.

In this controller class first we need to import intervention image library, for in this file first we need to write use Image; statement. By using this statement, we can import intervention image library in this controller class.

In this controller class we have make following method.

index() - This is the root method of this controller. This method has been load resize.blade.php file in browser.

resize_image(Request $request) - This method has been received request for image upload.
In this method first it has validate form data by using Laravel validator.
After this, it has make new name for image file. After making new name, first it has resize image by using intervention image library and upload resize image in thumbnail folder.
Once resize or crop image has been save into public directory thumbnail folder. Then after it has process for upload original size image in public directory images folder. After uploading and resize image, it will redirect url to it's previous location with data like success message and new image name.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

use Image;

class ResizeController extends Controller
{
    function index()
    {
     return view('resize');
    }

    function resize_image(Request $request)
    {
     $this->validate($request, [
      'image'  => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
     ]);

     $image = $request->file('image');

     $image_name = time() . '.' . $image->getClientOriginalExtension();

     $destinationPath = public_path('/thumbnail');

     $resize_image = Image::make($image->getRealPath());

     $resize_image->resize(150, 150, function($constraint){
      $constraint->aspectRatio();
     })->save($destinationPath . '/' . $image_name);

     $destinationPath = public_path('/images');

     $image->move($destinationPath, $image_name);

     return back()
       ->with('success', 'Image Upload successful')
       ->with('imageName', $image_name);

    }
}



Make View Blade File in Laravel 5.8


View blade file in Laravel has been use for display html data on web page. In Laravel view file has been store in resources/views folder and here we have store resize.blade.php file. In this file we have make html form for uploading image. And by using Laravel expression, here it will display success or validation error and it will also display uploaded and resize image on web page after uploading of image.


<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel 5.8 - Image Upload and Resize</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">
   <br />
   <h1 align="center">Laravel 5.8 - Image Upload and Resize</h1>
   <br />   
   <form method="post" action="{{ url('resize/resize_image') }}" enctype="multipart/form-data">
    @CSRF
    <div class="row">
           <div class="col-md-4" align="right">
            <h3>Select Image</h3>
           </div>
           <div class="col-md-4">
            <br />
               <input type="file" name="image" class="image" />
           </div>
           <div class="col-md-2">
            <br />
               <button type="submit" class="btn btn-success">Upload Image</button>
           </div>
       </div>
   </form>
   <br />
   @if(count($errors) > 0)
    <div class="alert alert-danger">
           <ul>
           @foreach($errors->all() as $error)
            <li>{{ $error }}</li>
           @endforeach
           </ul>
       </div>
   @endif

   @if($message = Session::get('success'))
   <div class="alert alert-success alert-block">
       <button type="button" class="close" data-dismiss="alert">×</button>    
       <strong>{{ $message }}</strong>
   </div>
   <div class="row">
       <div class="col-md-6">
           <strong>Original Image:</strong>
           <br/>
           <img src="/images/{{ Session::get('imageName') }}" class="img-responsive img-thumbnail">
       </div>
       <div class="col-md-4">
           <strong>Thumbnail Image:</strong>
           <br/>
           <img src="/thumbnail/{{ Session::get('imageName') }}" class="img-thumbnail" />
       </div>
   </div>
   @endif
  </div>
 </body>
</html>



Set Route in Laravel 5.8


Once your all code is ready, lastly we have to set the route of Controller method. For this we have to go routes/web.php file, and in this file we have to define the root of controller method.


Route::get('resize', 'ResizeController@index');

Route::post('resize/resize_image', 'ResizeController@resize_image');


Run Laravel 5.8 Application


Now we have to check output in browser. For this we have to again go to command prompt and write following command.


php artisan serve


This command will start Laravel server and it will give you http://127.0.0.1:8000 this base url of your Laravel application. For check above code you have to hit following url.


http://127.0.0.1:8000/resize


By hit above URL you can upload image and check image has been properly resize or not. So from this post you can learn something new lesson like resize image with upload in Laravel 5.8 framework.

Saturday, 31 August 2019

Front-end Form Validation using Parsleys.js in Laravel 5.8



Do you know why Form Validation is needed? This is because Validation of Form Data is required for prevent web application form entered invalid users data. If we have not perform form validation, then it will increase the our system security vulnerabilities. And there is increase the chances of attack of header injection, SQL injections or cross-site scripting.

Now What is Form validation, Form Validation means the check input data which has been submitted by the users of our system. There are two ways we can perform Form validation. One is Client Side Form validation and another one is server side Form Validation.

Here we have use Laravel 5.8 framework for web development. And here we will learn How can we validate user entered input data in our Laravel application at client side. For Validate users input data at client side, for this we have use Parsleys.js javascript library.

Parsley is the Javascript form validation library. By using this javascript library we can perform form validation at frontend that means it will validate form input data at client machine, if all input data has been valid then after it will send this data to server for do database operation. In this tutorial, we will seen how can we use Parsley.js library for client-side form validation in Laravel 5.8 application. Below you can find step by step process for validate form data in Laravel 5.8 application.

  • Download and Install Laravel 5.8 Framework
  • Make Database Connection in Laravel 5.8
  • Create Controller in Laravel 5.8
  • Create View Blade File in Laravel 5.8
  • Set Route in Laravel 5.8
  • Run Laravel 5.8 Application


Download and Install Laravel 5.8 Framework


If you has use Laravel for your Web Development, then first you have to download and install Laravel 5.8 application. For this you have to go to command prompt. And in command prompt first you have to go folder in which you want to download and install Laravel 5.8 framework. After this you have to run "composer" command, because Compose has maintain the laravel package. And after this you have write below command, it will download and install Laravel latest version in your local computer.


composer create-project --prefer-dist laravel/laravel form_validation


Make Database Connection in Laravel 5.8


After downloading and installing of Laravel framework, now we want to make database connection. For we have to open .env file and in this file we have to define Mysql Database configuration.


DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=


Once you have make Mysql Database connection, now you have to make table in your Database, for this you have run following sql script. This script will make tbl_register table in your Mysql Database.


--
-- Table structure for table `tbl_register`
--

CREATE TABLE `tbl_register` (
  `register_id` int(11) NOT NULL,
  `first_name` varchar(150) NOT NULL,
  `last_name` varchar(150) NOT NULL,
  `email` varchar(150) NOT NULL,
  `password` varchar(150) NOT NULL,
  `website` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for table `tbl_register`
--
ALTER TABLE `tbl_register`
  ADD PRIMARY KEY (`register_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_register`
--
ALTER TABLE `tbl_register`
  MODIFY `register_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;


Create Controller in Laravel 5.8


In Larave framework, you have to make controller for handle http reqest. In Laravel controller class has been store in app/Http/Controllers and here we have to make FormValidationController.php file. In controller we have write user DB; statement for perform Database side operation. Here we have make following method in controller.

index() - This is the root method of this Form Validation controller. It will load form_validation.blade.php file in browser for display output.

insert(Request $request) - This method has been used for insert data into Mysql table. This method has been received Ajax request from blade file for insert data and this method has give response to Ajax request in json format.

app/Http/Controllers/FormValidationController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use DB;

class FormValidationController extends Controller
{
    function index()
    {
     return view('form_validation');
    }

    function insert(Request $request)
    {
     if(request()->ajax())
     {
      $data = array(
       'first_name' => $request->get('first_name'),
       'last_name'  => $request->get('last_name'),
       'email'   => $request->get('email'),
       'password'  => $request->get('password'),
       'website'  => $request->get('website')
      );

      DB::table('tbl_register')->insert($data);

      return response()->json(['success' => 'Data Added']);
     }
    }
}



Create View Blade File in Laravel 5.8


Now we have come to main part of this tutorial. Here we have to make View Blade file in Laravel 5.8 framework, this file has been used for display html output file on web page. This file has been store in resources/view file. And here we have to make form_validation.blade.php file.

In this file we have imported jQuery Library, Bootstrap library and for form validation we have use Parsley.js javascript library also. For use Parsley.js library, you have to first import jQuery library also. Without jQuery library we cannot use Parsley.js library.Here we have make simple Registration form for perform form validation by using Parsley.js library. Below you can find parsley.js attribute which has been used for form validation in this post.



Parsley.js validators Description
required By using this attribute, it will add input file value if required for submit form data.
data-parsley-pattern="[a-zA-Z]+$" It will check input field value has been match with the define regular expression, if value not match it will trigger validation error.
data-parsley-type="email" This will check if input field value is valid email or not. If input field value is invalid email, then it will trigger validation error.
data-parsley-length="[8,16]" This validator check input field value length has been between define range, if length is not between define range then it will trigger error.
data-parsley-equalto="#password" This validator will check this input field value must be equal to value of input field with id password, if value is not match with define input field then it will trigger error.
data-parsley-trigger="keyup" This validator will trigger validation error on key up event.

Below you can find which Parsley.js library method here in this tutorial.

Parsley.js Method Description
$('#validate_form').parsley(); This method will initialize Parsley.js library on define form id.
$('#validate_form').parsley().isValid() This method will return true, if all form data has been proper.
$('#validate_form').parsley().reset(); This method will remove all formatting which has been generated by Parsley.js library.

After validating all form data, it will send Ajax request to Laravel controller insert() method.

resources/views/form_validation.blade.php

<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel 5.8 - Client Side Form Validation using Parsleys.js</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>
  <script src="http://parsleyjs.org/dist/parsley.js"></script>
  <style>
  .box
  {
   width:100%;
   max-width:600px;
   background-color:#f9f9f9;
   border:1px solid #ccc;
   border-radius:5px;
   padding:16px;
   margin:0 auto;
  }
  input.parsley-success,
  select.parsley-success,
  textarea.parsley-success {
    color: #468847;
    background-color: #DFF0D8;
    border: 1px solid #D6E9C6;
  }

  input.parsley-error,
  select.parsley-error,
  textarea.parsley-error {
    color: #B94A48;
    background-color: #F2DEDE;
    border: 1px solid #EED3D7;
  }

  .parsley-errors-list {
    margin: 2px 0 3px;
    padding: 0;
    list-style-type: none;
    font-size: 0.9em;
    line-height: 0.9em;
    opacity: 0;

    transition: all .3s ease-in;
    -o-transition: all .3s ease-in;
    -moz-transition: all .3s ease-in;
    -webkit-transition: all .3s ease-in;
  }

  .parsley-errors-list.filled {
    opacity: 1;
  }
  
  .parsley-type, .parsley-required, .parsley-equalto, .parsley-pattern, .parsley-length{
   color:#ff0000;
  }
  
  </style>

 </head>
 <body>
  <div class="container">    
     <br />
     <h3 align="center">Laravel 5.8 - Client Side Form Validation using Parsleys.js</h3>
     <br />
     <div class="box">
    <form id="validate_form">

     @CSRF

     <div class="row">
      <div class="col-xs-6">
       <div class="form-group">
        <label>First Name</label>
        <input type="text" name="first_name" id="first_name" class="form-control" placeholder="Enter First Name" required data-parsley-pattern="[a-zA-Z]+$" data-parsley-trigger="keyup" />
       </div>
      </div>
      <div class="col-xs-6">
       <div class="form-group">
        <label>Last Name</label>
        <input type="text" name="last_name" id="last_name" class="form-control" placeholder="Enter Last Name" required data-parsley-pattern="[a-zA-Z]+$" data-parsley-trigger="keyup" />
       </div>
      </div>
     </div>
     <div class="form-group">
      <label>Email</label>
      <input type="text" name="email" id="email" class="form-control" placeholder="Email" required data-parsley-type="email" data-parsley-trigger="keyup" />
     </div>
     <div class="form-group">
      <label for="password">Password</label>
      <input type="password" name="password" id="password" class="form-control" placeholder="Password" required data-parsley-length="[8,16]" data-parsley-trigger="keyup" />
     </div>
     <div class="form-group">
      <label>Confirm Password</label>
      <input type="password" name="confirm_password" id="confirm_password" class="form-control" placeholder="Confirm Password" required data-parsley-equalto="#password" data-parsley-trigger="keyup" />
     </div>
     <div class="form-group">
      <label>Website</label>
      <input type="text" name="website" id="website" class="form-control" data-parsley-type="url" data-parsley-trigger="keyup" />
     </div>
     <div class="form-group">
      <div class="checkbox">
       <label> <input type="checkbox" name="check_rules" id="check_rules" required />I Accept the Terms & Conditions</label>
      </div>
     </div>
     <div class="form-group">
      <input type="submit" name="submit" id="submit" value="Submit" class="btn btn-success" />
     </div>

    </form>

   </div>
  </div>
 </body>
</html>
<script>
$(document).ready(function(){

 $('#validate_form').parsley();

 $('#validate_form').on('submit', function(event){
  event.preventDefault();

  if($('#validate_form').parsley().isValid())
  {
   $.ajax({
    url: '{{ route("form-validation.insert") }}',
    method:"POST",
    data:$(this).serialize(),
    dataType:"json",
    beforeSend:function()
    {
     $('#submit').attr('disabled', 'disabled');
     $('#submit').val('Submitting...');
    },
    success:function(data)
    {
     $('#validate_form')[0].reset();
     $('#validate_form').parsley().reset();
     $('#submit').attr('disabled', false);
     $('#submit').val('Submit');
     alert(data.success);
    }
   });
  }
 });

});
</script>



Set Route in Laravel 5.8


Once all code is ready, lastly we have to set the route of controller method. For this we have to open routes/web.php file.

routes/web.php

Route::get('form-validation', 'FormValidationController@index');

Route::post('form-validation/insert', 'FormValidationController@insert')->name('form-validation.insert');


Run Laravel 5.8 Application


For run Laravel application, we have to again go to command prompt and write following command.


php artisan serve


This command will start laravel server, it will provide us base url of our Laravel application. For run above tutorial, we have to type following url in your browser.


http://127.0.0.1:8000/form-validation


So, this way we can perform client-side or front-end side form validation by using Parsley.js library in Laravel 5.8 framework without write any line of code.

Wednesday, 28 August 2019

How To Move Your Blog From WordPress.Com To Your Own Hosting Server



Are you getting frustrated with WordPress.com services?

Why?

Wait. I will tell you!!

WordPress.com has a lot of limitations, from less monetization ability, plugins installation issues, to third party ads on your users, and so on. Newbies generally start using WordPress.com and realize its drawbacks later and wish to switch to its hosting server.

Despite that, if you are planning to build a serious business, you will realize that WordPress.com is not a skillful option to go with. In case of premium options, such as audio/video uploads, custom domain, advertisement display, extra space, you have to pay for the extra amount. With the lack of security and control, WordPress.com shows an inability for output generation from the blog.

If you are facing these issues, it's time to switch to your hosting server.

The aim behind this article is to present the methods or the steps to change your blog from WordPress.org to your server. Hiring the Best WordPress Development Outsourcing company is also a favorable approach for effective work. According to the demands and budget, you can choose the path that will be suitable for you. Let's proceed without wasting more time!!

Table of Content


Why You Should Move To Your Own Hosting Server

Steps to follow to move from WordPress.com to your hosting server

  • Step #1 Register a domain & find a hosting provider
  • Step #2 Install WordPress
  • Step #3 Find & install a theme
  • Step #4 Export Data From Your WordPress.com Server
  • Step #5 Import Data On Your New Domain
  • Step #6 Redirect Your WordPress.com Site
  • Conclusion

Why You Should Move To Your Own Hosting Server


When moving from WordPress.com to another host, you're going to have to pay for hosting. Fortunately, there are many benefits to upgrading.

Here are several reasons to move from WordPress.com to a self-hosted solution:

  • It's only good for community-based, low traffic or personal sites.
  • It does not support email hosting.
  • You can't use custom plugins and affiliate links.
  • If you don't abide by WordPress' terms of service, you could get banned by them.
  • It can't handle the growing requirements of a business.
  • Limited theme choice – several professional themes are not supported by WordPress.com.
  • You cannot make changes in WordPress theme structures as you are limited by customization restrictions.

Now that you know why you need web hosting, let's talk about getting set up.

Steps to follow to move from WordPress.com to your hosting server


Step #1 Register a domain & find a hosting provider


First, register a domain name of your choice. Next, choose a hosting service. Hosts are not hard to find – do a quick Google search.

Step #2 Install WordPress


After you've registered with a hosting company, you need to install the WordPress CMS on your site.

With most hosts, it only takes a few clicks to install WordPress. If you run into any problems, again, Google is your friend.

Step #3 Find & install a theme


You can find many great themes in WordPress. Premium themes such as the Genesis Framework – on the other hand, might require some digging.

Oftentimes, you pay for what you get. Free themes might seem nice on the outside, but they break easily. Use WordPress own Twenty Sixteen or Twenty Fifteen themes as a starting point if you don't have a budget for themes right now.

Step #4 Export Data From Your WordPress.com Server


Log in to your account at WordPress.com and click on "My Sites" in the top left-hand corner if it isn't already selected. Scroll down in the menu bar until you see "Settings" (it should be at the bottom)", and then click on "Export" in the primary window.




Then, export all content. You'll be prompted to save an XML file to your hard drive, which contains all the data of your WordPress site, including pages, categories, posts, tags, comments, and so on.



Step #5 Import Data On Your New Domain


Log into WordPress on your self-hosted site, if you aren't logged in already.




From the left-hand menu bar, roll over "Tools", and then click on "Import". Scroll down until you see "WordPress", and click on the "Install Now" link, which will install the WordPress Importer plugin. Once installed, activate the plugin and run it.






You'll be navigated to browse for a file on your hard drive. Upload your XML file from earlier, click on "Upload file and import", and the Importer should do the rest of the work for you.

Step #6 Redirect Your WordPress.com Site


First, you'll need to go to this link. It may seem counter-intuitive, but it's the easiest way to redirect your site.

Now, click on the site you want to redirect (if you have more than one connected to your WordPress.com) account.

Enter the new domain where you want your traffic to redirect to, then click on "Go". Yes, you must pay for the redirect option. Follow the checkout process, and you're done this part of the process.




But there's one more thing you should check, which is your permalink structure. In most cases, you can keep the defaults, and everything should work fine. But if your permalink structure is different on your domain than it was on your WordPress.com blog, the forwarding may not work properly. Double-check to make sure.

Conclusion


So, this was an easy-to-follow tutorial comprising of only necessary steps to move your blog from WordPress.com to your hosting server. Try out these steps and see how easily you migrate to your self-hosted domain. Enjoy the ride!

About the Author


Emily Johns is a web developer and IT consultant at WordSuccor, a WordPress conversion company. She is dived through open-source code for over a decade and shares everything about WordPress and new Web design technologies. You can find her on Twitter!

Saturday, 24 August 2019

Developed To-Do List in PHP using Ajax

Developed To-Do List in PHP using Ajax - 1




Developed To-Do List in PHP using Ajax - 2




Developed To-Do List in PHP using Ajax - 3




Developed To-Do List in PHP using Ajax - 4





This one more post on making single page application using PHP PDO with Ajax. Here we will make a simple but very useful Ajax based To-do List Application using PHP, jQuery, Bootsrap and MySQL. During the process of developing To Do List App, we will discuss how can we use PHP PDO capability to play vital role with jQuery and Bootstrap with AJAX without page refresh functionality.

After publishing some tutorial on different PHP PDO based application, now we have been working with many different technologies for build To Do List script. So, lastly we have build this simple to-do list in which different user can create own to do list, checked to do list or update to do list status, or even user after completing to do list task they can also delete to do list item also. For this functionality, here we have use PHP PDO with Ajax jQuery, Bootstrap and Mysql database. This is database to do list application, in which data has been store in center database. All user to do list has been store in single database. Below you can find step by step process with source code also.






Make Database


For make any web based application, first we need to make table in Mysql database. For this we have to run following sql script. It will make task_list table in your local mysql database.




--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `task_list`
--

CREATE TABLE `task_list` (
  `task_list_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `task_details` text NOT NULL,
  `task_status` enum('no','yes') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `task_list`
--
ALTER TABLE `task_list`
  ADD PRIMARY KEY (`task_list_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `task_list`
--
ALTER TABLE `task_list`
  MODIFY `task_list_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;


After this for make database connection, you have to write following php script. It will make database connection with your PHP script.


<?php
//database_connection.php

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

session_start();

$_SESSION["user_id"] = "1";

?>


index.php


This is the main page of this to do list app, and in this file we have write all html code, jQuery and Ajax code.

In this file, first we want to load login user all to do list, for this here we have use PHP script for display to do list on web page. In each to do list litem, we have generate dynamic id attribute value, which we use in jQuery code. For remove particular to do list item also, we will use id of particular to do list. Here we have use Bootstrap CSS library for display to do list on web page.

After this we want to add or create new item in to do list. For this first we have make one HTML form. After this, by using jQuery code we have write some validation code and for submit form data to server, here we have also write Ajax request, which has send request to add_task.php file for insert data into Mysql table.

Once you have add item into To-Do List then after we want to checked that to-do list. For this here we have use Ajax request, which have send request to update_task.php file for change the status of to-do list. Here we have use CSS text-decoration:line-through property. It will draw line on text which has been display has this has been checked.


<?php

//index.php

include('database_connection.php');

$query = "
 SELECT * FROM task_list 
 WHERE user_id = '".$_SESSION["user_id"]."' 
 ORDER BY task_list_id DESC
";

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

$statement->execute();

$result = $statement->fetchAll();

?>

<!DOCTYPE html>
<html>
 <head>
  <title>Developed To-Do List in PHP using Ajax</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>
  <style>
   body
   {
    font-family: 'Comic Sans MS';
   }

   .list-group-item
   {
    font-size: 26px;
   }
  </style>
 </head>
 <body>
  
  <br />
  <br />
  <div class="container">
   <h1 align="center">Developed To-Do List in PHP using Ajax - 4</h1>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <div class="row">
      <div class="col-md-9">
       <h3 class="panel-title">My To-Do List</h3>
      </div>
      <div class="col-md-3">
       
      </div>
     </div>
    </div>
      <div class="panel-body">
       <form method="post" id="to_do_form">
        <span id="message"></span>
        <div class="input-group">
         <input type="text" name="task_name" id="task_name" class="form-control input-lg" autocomplete="off" placeholder="Title..." />
         <div class="input-group-btn">
          <button type="submit" name="submit" id="submit" class="btn btn-success btn-lg"><span class="glyphicon glyphicon-plus"></span></button>
         </div>
        </div>
       </form>
       <br />
       <div class="list-group">
       <?php
       foreach($result as $row)
       {
        $style = '';
        if($row["task_status"] == 'yes')
        {
         $style = 'text-decoration: line-through';
        }
        echo '<a href="#" style="'.$style.'" class="list-group-item" id="list-group-item-'.$row["task_list_id"].'" data-id="'.$row["task_list_id"].'">'.$row["task_details"].' <span class="badge" data-id="'.$row["task_list_id"].'">X</span></a>';
       }
       ?>
       </div>
      </div>
     </div>
  </div>
 </body>
</html>

<script>
 
 $(document).ready(function(){
  
  $(document).on('submit', '#to_do_form', function(event){
   event.preventDefault();

   if($('#task_name').val() == '')
   {
    $('#message').html('<div class="alert alert-danger">Enter Task Details</div>');
    return false;
   }
   else
   {
    $('#submit').attr('disabled', 'disabled');
    $.ajax({
     url:"add_task.php",
     method:"POST",
     data:$(this).serialize(),
     success:function(data)
     {
      $('#submit').attr('disabled', false);
      $('#to_do_form')[0].reset();
      $('.list-group').prepend(data);
     }
    })
   }
  });

  $(document).on('click', '.list-group-item', function(){
   var task_list_id = $(this).data('id');
   $.ajax({
    url:"update_task.php",
    method:"POST",
    data:{task_list_id:task_list_id},
    success:function(data)
    {
     $('#list-group-item-'+task_list_id).css('text-decoration', 'line-through');
    }
   })
  });

  $(document).on('click', '.badge', function(){
   var task_list_id = $(this).data('id');
   $.ajax({
    url:"delete_task.php",
    method:"POST",
    data:{task_list_id:task_list_id},
    success:function(data)
    {
     $('#list-group-item-'+task_list_id).fadeOut('slow');
    }
   })
  });

 });
</script>




add_task.php


This file has been received ajax request for insert or add or create new to do list item. Here we have use PHP PDO script for insert data into Mysql table. Once the data has been added into Mysql table, then it has send last inserted to do list details has been send to Ajax request, which it will display on web page without refresh of web page.


<?php

//add_task.php

include('database_connection.php');

if($_POST["task_name"])
{
 $data = array(
  ':user_id'  => $_SESSION['user_id'],
  ':task_details' => trim($_POST["task_name"]),
  ':task_status' => 'no'
 );

 $query = "
 INSERT INTO task_list 
 (user_id, task_details, task_status) 
 VALUES (:user_id, :task_details, :task_status)
 ";

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

 if($statement->execute($data))
 {
  $task_list_id = $connect->lastInsertId();

  echo '<a href="#" class="list-group-item" id="list-group-item-'.$task_list_id.'" data-id="'.$task_list_id.'">'.$_POST["task_name"].' <span class="badge" data-id="'.$task_list_id.'">X</span></a>';
 }
}


?>


update_task.php


This PHP file has been received Ajax request for update the status of to do list task. On this page first we have make database connection and then after we have check any data has been received or not if received then it has been proceed for update the status of task list. For update data here we have use PHP PDO script. After done updating of status then it has send response to Ajax request.


<?php

//update_task.php

include('database_connection.php');

if($_POST["task_list_id"])
{
 $data = array(
  ':task_status'  => 'yes',
  ':task_list_id'  => $_POST["task_list_id"]
 );

 $query = "
 UPDATE task_list 
 SET task_status = :task_status 
 WHERE task_list_id = :task_list_id
 ";

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

 if($statement->execute($data))
 {
  echo 'done';
 }
}

?>


delete_task.php


This script has been used for delete or remove task list. This script has been received ajax request for remove to do list from database and after successfully removed of data it will send response to Ajax request.


<?php

//delete_task.php

include('database_connection.php');

if($_POST["task_list_id"])
{
 $data = array(
  ':task_list_id'  => $_POST['task_list_id']
 );

 $query = "
 DELETE FROM task_list  
 WHERE task_list_id = :task_list_id
 ";

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

 if($statement->execute($data))
 {
  echo 'done';
 }
}



?>


So, this is complete source of To-do List Crud application which has been build in PHP script with Ajax jQuery Bootstrap and Mysql Database.