Showing posts with label ajax progress bar with php. Show all posts
Showing posts with label ajax progress bar with php. Show all posts

Sunday, 3 November 2019

CSV Import Using AJAX Progress Bar in PHP

Part 1 - Upload CSV File using Ajax with PHP



Part 2 - Start Import CSV file data using Ajax



Part 3 - Start Import CSV file data using Ajax




This is another post on display PHP script process on progress bar using Ajax with jQuery. Here In this post we will show CSV file data import process on progress bar by using Ajax jquery with PHP script. Or in short Display CSV import process using Ajax progress bar.

Now you have one question arise in your mind why we want to display import process of CSV file data on progress bar. This is one very useful feature for impove your UI, because if there is large data in your CSV file for import into Mysql data, then at that time your PHP script will display time out error on web page. And it will very difficult import large amount of CSV file data into Mysql database.

For solve this problem, here we have make one php script, which will solve the problem of PHP timeout error at the time of import of large CSV file. Because here we will import CSV file data into Mysql table in step by step and display how many data are process for import we will display on progress bar using Ajax with jQuery. So, if User has import CSV file, then he can view CSV file data importing process on web page in the form of progress bar. This all process will be done without refresh of web page, because here we have use Ajax technology with jQuery. Here we have use Bootstrap library for make progress bar.

There are many tutorials are available online for display file upload procress on progress bar in php script using Ajax, but there is no any post find on How to show CSV file data import process on progress bar using Ajax jQuery in PHP script. So, we have publish this tutorial, in which we have covered how to display real time mysql data import process on progress bar using Ajax with PHP. For make real time progress bar in PHP using Ajax, we have divided this tutorial into following part.

  • Upload CSV File using Ajax with PHP
  • Start Import CSV file data using Ajax
  • Display Import CSV File Data on progress bar using Ajax






Upload CSV File using Ajax with PHP


Here we will first upload CSV file on server by using PHP with Ajax. We can also directly fetch data from CSV file without uploading also, but here we want to display real time import process on progress bar, so we will first upload CSV file on server by using Ajax. Source code of uploading of CSV file using Ajax with PHP script you can find below.

index.php



<!DOCTYPE html>
<html>
 <head>
  <title>Import CSV File Data with Progress Bar 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>
 </head>
 <body>
  
  <br />
  <br />
  <div class="container">
   <h1 align="center">Import CSV File Data with Progress Bar in PHP using Ajax - 3</h1>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Import CSV File Data</h3>
    </div>
      <div class="panel-body">
       <span id="message"></span>
       <form id="sample_form" method="POST" enctype="multipart/form-data" class="form-horizontal">
        <div class="form-group">
         <label class="col-md-4 control-label">Select CSV File</label>
         <input type="file" name="file" id="file" />
        </div>
        <div class="form-group" align="center">
         <input type="hidden" name="hidden_field" value="1" />
         <input type="submit" name="import" id="import" class="btn btn-info" value="Import" />
        </div>
       </form>
       <div class="form-group" id="process" style="display:none;">
        <div class="progress">
         <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
          <span id="process_data">0</span> - <span id="total_data">0</span>
         </div>
        </div>
       </div>
      </div>
     </div>
  </div>
 </body>
</html>

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

  var clear_timer;

  $('#sample_form').on('submit', function(event){
   $('#message').html('');
   event.preventDefault();
   $.ajax({
    url:"upload.php",
    method:"POST",
    data: new FormData(this),
    dataType:"json",
    contentType:false,
    cache:false,
    processData:false,
    beforeSend:function(){
     $('#import').attr('disabled','disabled');
     $('#import').val('Importing');
    },
    success:function(data)
    {
     if(data.success)
     {
      $('#total_data').text(data.total_line);

      $('#message').html('<div class="alert alert-success">CSV File Uploaded</div>');
     }
     if(data.error)
     {
      $('#message').html('<div class="alert alert-danger">'+data.error+'</div>');
      $('#import').attr('disabled',false);
      $('#import').val('Import');
     }
    }
   })
  });

 });
</script>


upload.php



<?php

//upload.php

if(isset($_POST['hidden_field']))
{
 $error = '';
 $total_line = '';
 session_start();
 if($_FILES['file']['name'] != '')
 {
  $allowed_extension = array('csv');
  $file_array = explode(".", $_FILES["file"]["name"]);
  $extension = end($file_array);
  if(in_array($extension, $allowed_extension))
  {
   $new_file_name = rand() . '.' . $extension;
   $_SESSION['csv_file_name'] = $new_file_name;
   move_uploaded_file($_FILES['file']['tmp_name'], 'file/'.$new_file_name);
   $file_content = file('file/'. $new_file_name, FILE_SKIP_EMPTY_LINES);
   $total_line = count($file_content);
  }
  else
  {
   $error = 'Only CSV file format is allowed';
  }
 }
 else
 {
  $error = 'Please Select File';
 }

 if($error != '')
 {
  $output = array(
   'error'  => $error
  );
 } 
 else
 {
  $output = array(
   'success'  => true,
   'total_line' => ($total_line - 1)
  );
 }

 echo json_encode($output);
}

?>


Start Import CSV file data using Ajax


Once CSV file has been store into folder, then after we want to start import CSV data into Mysql database. For start import csv file data, here we have use Ajax request, which will be triggered after successfully upload CSV file, and it will send Ajax request to PHP script for read data from CSV file and start importing into Mysql table.

index.php



<!DOCTYPE html>
<html>
 <head>
  <title>Import CSV File Data with Progress Bar 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>
 </head>
 <body>
  
  <br />
  <br />
  <div class="container">
   <h1 align="center">Import CSV File Data with Progress Bar in PHP using Ajax - 3</h1>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Import CSV File Data</h3>
    </div>
      <div class="panel-body">
       <span id="message"></span>
       <form id="sample_form" method="POST" enctype="multipart/form-data" class="form-horizontal">
        <div class="form-group">
         <label class="col-md-4 control-label">Select CSV File</label>
         <input type="file" name="file" id="file" />
        </div>
        <div class="form-group" align="center">
         <input type="hidden" name="hidden_field" value="1" />
         <input type="submit" name="import" id="import" class="btn btn-info" value="Import" />
        </div>
       </form>
       <div class="form-group" id="process" style="display:none;">
        <div class="progress">
         <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
          <span id="process_data">0</span> - <span id="total_data">0</span>
         </div>
        </div>
       </div>
      </div>
     </div>
  </div>
 </body>
</html>

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

  var clear_timer;

  $('#sample_form').on('submit', function(event){
   $('#message').html('');
   event.preventDefault();
   $.ajax({
    url:"upload.php",
    method:"POST",
    data: new FormData(this),
    dataType:"json",
    contentType:false,
    cache:false,
    processData:false,
    beforeSend:function(){
     $('#import').attr('disabled','disabled');
     $('#import').val('Importing');
    },
    success:function(data)
    {
     if(data.success)
     {
      $('#total_data').text(data.total_line);

      start_import();

      //$('#message').html('<div class="alert alert-success">CSV File Uploaded</div>');
     }
     if(data.error)
     {
      $('#message').html('<div class="alert alert-danger">'+data.error+'</div>');
      $('#import').attr('disabled',false);
      $('#import').val('Import');
     }
    }
   })
  });

  function start_import()
  {
   $('#process').css('display', 'block');
   $.ajax({
    url:"import.php",
    success:function()
    {

    }
   })
  }

 });
</script>


import.php



<?php

//import.php

header('Content-type: text/html; charset=utf-8');
header("Cache-Control: no-cache, must-revalidate");
header ("Pragma: no-cache");

set_time_limit(0);

ob_implicit_flush(1);

session_start();

if(isset($_SESSION['csv_file_name']))
{
 $connect = new PDO("mysql:host=localhost; dbname=testing", "root", "");

 $file_data = fopen('file/' . $_SESSION['csv_file_name'], 'r');

 fgetcsv($file_data);

 while($row = fgetcsv($file_data))
 {
  $data = array(
   ':first_name' => $row[0],
   ':last_name' => $row[1]
  );

  $query = "
  INSERT INTO tbl_sample (first_name, last_name) 
     VALUES (:first_name, :last_name)
  ";

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

  $statement->execute($data);

  sleep(1);

  if(ob_get_level() > 0)
  {
   ob_end_flush();
  }
 }

 unset($_SESSION['csv_file_name']);
}

?>


Display Import CSV File Data on progress bar using Ajax


Once CSV file is uploaded and start importing data from CSV file to Mysql Database, now in your mind question will arise how to display CSV data importing process on progress bar. For this also, we will send continously send Ajax request for fetech how many number of data are processed based on that number progress bar will display data import process. It will continously send request for fetch number of data are process until all data are imported into mysql table. For this here we have use jQuery setInterval() and clearInterval() callback function has been used.

index.php



<!DOCTYPE html>
<html>
 <head>
  <title>Import CSV File Data with Progress Bar 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>
 </head>
 <body>
  
  <br />
  <br />
  <div class="container">
   <h1 align="center">Import CSV File Data with Progress Bar in PHP using Ajax - 3</h1>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Import CSV File Data</h3>
    </div>
      <div class="panel-body">
       <span id="message"></span>
       <form id="sample_form" method="POST" enctype="multipart/form-data" class="form-horizontal">
        <div class="form-group">
         <label class="col-md-4 control-label">Select CSV File</label>
         <input type="file" name="file" id="file" />
        </div>
        <div class="form-group" align="center">
         <input type="hidden" name="hidden_field" value="1" />
         <input type="submit" name="import" id="import" class="btn btn-info" value="Import" />
        </div>
       </form>
       <div class="form-group" id="process" style="display:none;">
        <div class="progress">
         <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
          <span id="process_data">0</span> - <span id="total_data">0</span>
         </div>
        </div>
       </div>
      </div>
     </div>
  </div>
 </body>
</html>

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

  var clear_timer;

  $('#sample_form').on('submit', function(event){
   $('#message').html('');
   event.preventDefault();
   $.ajax({
    url:"upload.php",
    method:"POST",
    data: new FormData(this),
    dataType:"json",
    contentType:false,
    cache:false,
    processData:false,
    beforeSend:function(){
     $('#import').attr('disabled','disabled');
     $('#import').val('Importing');
    },
    success:function(data)
    {
     if(data.success)
     {
      $('#total_data').text(data.total_line);

      start_import();

      clear_timer = setInterval(get_import_data, 2000);

      //$('#message').html('<div class="alert alert-success">CSV File Uploaded</div>');
     }
     if(data.error)
     {
      $('#message').html('<div class="alert alert-danger">'+data.error+'</div>');
      $('#import').attr('disabled',false);
      $('#import').val('Import');
     }
    }
   })
  });

  function start_import()
  {
   $('#process').css('display', 'block');
   $.ajax({
    url:"import.php",
    success:function()
    {

    }
   })
  }

  function get_import_data()
  {
   $.ajax({
    url:"process.php",
    success:function(data)
    {
     var total_data = $('#total_data').text();
     var width = Math.round((data/total_data)*100);
     $('#process_data').text(data);
     $('.progress-bar').css('width', width + '%');
     if(width >= 100)
     {
      clearInterval(clear_timer);
      $('#process').css('display', 'none');
      $('#file').val('');
      $('#message').html('<div class="alert alert-success">Data Successfully Imported</div>');
      $('#import').attr('disabled',false);
      $('#import').val('Import');
     }
    }
   })
  }

 });
</script>


process.php



<?php

//process.php

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

$query = "SELECT * FROM tbl_sample";

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

$statement->execute();

echo $statement->rowCount();

?>


This tutorial is make for learning purpose, you have make required changes as per your requirement. Above you have complete step by step process for CSV file data importing process on progress bar using PHP script with Ajax jQuery Bootstrap and Mysql database. If you want to get complete source code of this PHP Ajax jQuery tutorial, you can download source code in zip file by click on below link.





Sunday, 22 September 2019

How to Create Progress Bar for Data Insert in PHP using Ajax



We all know how to insert data using PHP with Ajax but if you know how to increment a progress bar while insert data into mysql database in php using Ajax with jQuery and Bootstrap. There are many viewers reader of our blog has requested us to publish post on How to display data inserting process on progress bar with PHP using Ajax jQuery and Bootstrap.

First we want to know why we have use progress bar in web development. There are many different ways we have use progress bar in our web application. e.g For display file downloading process we have use progress bar. For display file uploading process we have use progress bar in our web page. And event for any form data submission process like inserting of data or updating of data process we can also display progress bar. So, user can understand their data has been process. So, this way we have use progress bar in our web development.

Now we have come to our topic like how to create process bar while inserting of data using PHP with Ajax. This is one type of feature which will increase your website user interface. Because it has define processing of data on web page using progress bar element.

In below example, we have define how to make progress bar by using jQuery Bootstrap with Ajax and PHP. Here we have use PHP script for server side processing of data and for client side we have use Ajax jQuery and Bootstrap. Ajax has been used for send data to server, jQuery has been used for form data validation and continue execution of function and lastly bootstrap has been used for make progress bar. Now when user has filled form and all data successfully validated then it will send data to server using Ajax, when data has insert into mysql database table, then at that time it will display inserting of data in progress bar, so it will increase website UI. So, this way we can display insert data process in progress bar in PHP with Ajax, jQuery and Bootstrap. Below you can find complete source with online demo also.







Source Code


Database



--
-- Database: `testing`
--

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

--
-- Table structure for table `tbl_sample`
--

CREATE TABLE `tbl_sample` (
  `id` int(11) NOT NULL,
  `first_name` varchar(250) NOT NULL,
  `last_name` varchar(250) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

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

--
-- AUTO_INCREMENT for dumped tables
--

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


index.php



<?php

//index.php

?>

<!DOCTYPE html>
<html>
 <head>
  <title>How to Create Progress Bar for Data Insert 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>
 </head>
 <body>
  
  <br />
  <br />
  <div class="container">
   <h1 align="center">How to Create Progress Bar for Data Insert in PHP using Ajax</h1>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Enter Data</h3>
    </div>
      <div class="panel-body">
       <span id="success_message"></span>
       <form method="post" id="sample_form">
        <div class="form-group">
         <label>First Name</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="form-group">
         <label>Last Name</label>
         <input type="text" name="last_name" id="last_name" class="form-control" />
         <span id="last_name_error" class="text-danger"></span>
        </div>
        <div class="form-group" align="center">
         <input type="submit" name="save" id="save" class="btn btn-info" value="Save" />
        </div>
       </form>
       <div class="form-group" id="process" style="display:none;">
        <div class="progress">
       <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" style="">
       </div>
      </div>
       </div>
      </div>
     </div>
  </div>
 </body>
</html>

<script>
 
 $(document).ready(function(){
  
  $('#sample_form').on('submit', function(event){
   event.preventDefault();
   var count_error = 0;

   if($('#first_name').val() == '')
   {
    $('#first_name_error').text('First Name is required');
    count_error++;
   }
   else
   {
    $('#first_name_error').text('');
   }

   if($('#last_name').val() == '')
   {
    $('#last_name_error').text('Last Name is required');
    count_error++;
   }
   else
   {
    $('#last_name_error').text('');
   }

   if(count_error == 0)
   {
    $.ajax({
     url:"process.php",
     method:"POST",
     data:$(this).serialize(),
     beforeSend:function()
     {
      $('#save').attr('disabled', 'disabled');
      $('#process').css('display', 'block');
     },
     success:function(data)
     {
      var percentage = 0;

      var timer = setInterval(function(){
       percentage = percentage + 20;
       progress_bar_process(percentage, timer);
      }, 1000);
     }
    })
   }
   else
   {
    return false;
   }
  });

  function progress_bar_process(percentage, timer)
  {
   $('.progress-bar').css('width', percentage + '%');
   if(percentage > 100)
   {
    clearInterval(timer);
    $('#sample_form')[0].reset();
    $('#process').css('display', 'none');
    $('.progress-bar').css('width', '0%');
    $('#save').attr('disabled', false);
    $('#success_message').html("<div class='alert alert-success'>Data Saved</div>");
    setTimeout(function(){
     $('#success_message').html('');
    }, 5000);
   }
  }

 });
</script>


process.php



<?php

//process.php

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

if(isset($_POST["first_name"]))
{
 $data = array(
  ':first_name'  => trim($_POST["first_name"]),
  ':last_name'  => trim($_POST["last_name"])
 );

 $query = "
 INSERT INTO tbl_sample 
 (first_name, last_name) 
 VALUES (:first_name, :last_name)
 ";

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

 $statement->execute($data);

 echo 'done';
 
}

?>