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.





0 comments:

Post a Comment