Thursday, February 6, 2020

Import CSV File Data With Progress Bar in PHP Using AJAX

 Import CSV File Data With Progress Bar in PHP Using AJAX

This is another post in the on-screen PHP script process in the progress bar using Ajax with jQuery. In this post we show the process of importing data from CSV files in the progress bar using Ajax-Jquery with PHP script. Or summarize the CSV import process using the Ajax progress bar.

Now you have a question: why do we want to show the process of importing data from CSV files in the progress bar? This is a very useful function to improve your user interface. If your CSV file contains large data to be imported into MySQL data, your PHP script will show a timeout error on the website. And it will be very difficult to import a large amount of data from CSV files into the MySQL database.

To solve this problem, we have created a PHP script here that fixes the problem of the PHP timeout error when importing a large CSV file. Because here we will import the data from the CSV file into the Mysql table step by step and show how much data is processed for the import, which we will display in the progress bar with Ajax with jQuery. When the user has imported the CSV file, you can see the process of importing data from the CSV file on the website in the form of a progress bar. This whole process is done without updating the website as we have used Ajax technology with jQuery here. Here we used the bootstrap library to create the progress bar.

There are many online tutorials that illustrate the process of loading files in the progress bar in the PHP script using Ajax. However, it is not searched for how the process of importing data from CSV files into the progress bar is displayed with Ajax jQuery in the PHP script. That is why we published this tutorial in which we explained how the process of importing MySQL data in real time is shown in the progress bar using Ajax with PHP. To create a real-time progress indicator in PHP using Ajax, we have divided this tutorial into the next part.


  • Upload a CSV file using Ajax and PHP
  • Start importing data from CSV files with Ajax
  • Use Ajax to display import data from CSV files in the progress bar



Using Ajax with PHP To Upload CSV File


Here we will first upload the CSV file to the server using PHP and Ajax. We can also retrieve data directly from the CSV file without loading it. Here, however, we want to show the import process in real time in the progress bar, so we first load the CSV file with Ajax on the server. The source code for loading CSV files with Ajax using PHP script can be found 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 </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


As soon as the CSV file has been saved in the folder, we would like to start importing the CSV data into the MySQL database. To start importing data from the CSV file, we used the Ajax request here, which is activated after the CSV file has been loaded successfully. The Ajax request is then sent to the PHP script to read the data from the CSV file and to start the import into the 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</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']);
}

?>


Using Ajax to Display Import CSV File Data on progress bar


As soon as the CSV file is loaded and the import of data from the CSV file into the MySQL database begins, the question arises how the process of importing CSV data should be shown in the progress bar. For this, too, we continuously send the Ajax request to Fetech as to how much data is processed based on the progress bar of this number, which the data import process shows. A request to retrieve the number of data processed is continuously sent until all data has been imported into the mysql table. We used jQuery setInterval () and the callback function clearInterval () for this. Csv" here.


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 </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 for learning purposes. You must make the necessary changes according to your requirements. Above is a complete step-by-step guide on how to import CSV file data into the progress bar using a PHP script with Ajax jQuery Bootstrap and the MySQL database.

0 comments:

Post a Comment

Please don't enter any spam link in the comment box.