Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

how to increment a progress bar while inserting data into database on button click in php

Posted on 2016-11-08
5
Medium Priority
?
1,519 Views
2 Endorsements
Last Modified: 2016-11-10
I have tried doing this but couldn't get it. Below is my code :
<script> 
    $(document).ready(function(){
        var $progressbar = $("#progressbar");
        $progressbar.show();
        $('#uploadForm').on('submit', function(e){
            e.preventDefault();
            $(function(){
                $progressbar.css('width', '30%');
            }); 
            $.ajax({
                url: "insertdata.php",
                type: "POST",
                data: new FormData(this),
                contentType: false,
                processData: false,
                success: function(data){
                    console.log(data);
                    if (data == 'T'){
                        $('#txtname').val("");
                        $('#txtsex').val("");
                        $('#txtage').val("");
                        $('#txterr').val('Record Inserted');
                        $progressbar.css('width', '100%');
                    }
                },
                error: function(data){
                alert("Something went wrong !");
            }
        });
    });
});
</script>

Open in new window


Code for Progress bar is as follows:
<div class="progress" style="margin-top:100px">
    <div class="progress-bar active" id="progressbar" role="progressbar" aria-valuenow="45" aria-valuemin="0" aria-valuemax="100" style="width: 0%">
        <span class="sr-only">0% Complete</span>
    </div>
</div>

Open in new window


insertdata.php In this file, insertion of data is processed.

Here working of my code is something like this: when the user presses the "Submit" button, progress bar shows 30% increase and when the process finishes 30% moves to 100%.

What I want to achieve is : Progress Bar should show progress ( percent by percent ) with the insertion of data into database, after Submit button is pressed.

How to achieve this?

Please help
2
Comment
Question by:Ratan Shastri
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
5 Comments
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 41879473
We have an article here at E-E that shows this exact application.
https://www.experts-exchange.com/articles/14519/A-jQuery-Progress-Bar.html

In order for the progress bar to be meaningful (or maybe even visible at all) the server-side process would need to run long enough for client/server communication to take place.  Typically a database insert is completed in milliseconds, so you might not see anything if the process completes quickly.  The article deliberately delays the background process so that the progress bar can be visible.
0
 
LVL 82

Expert Comment

by:leakim971
ID: 41879611
Without jQuery plugin :
<script> 
    $(document).ready(function(){
        var $progressbar = $("#progressbar");
        $progressbar.show();
        var updateProgressBar = function(evt) {
            if(evt.lengthComputable) {
                var percent = (evt.loaded*100)/evt.total;
                $(function(){
                    $progressbar.css('width', percent.toFixed(1) + '%');
                }); 
            }
        }
        $('#uploadForm').on('submit', function(e){
            e.preventDefault();
            $.ajax({
                xhr: function() {
                    var req = new XMLHttpRequest();
                    req.upload.addEventListener("progress", updateProgressBar, false);
                    req.addEventListener("progress", updateProgressBar, false);
                    return req;
                },
                url: "insertdata.php",
                type: "POST",
                data: new FormData(this),
                contentType: false,
                processData: false,
                success: function(data){
                    console.log(data);
                    if (data == 'T'){
                        $('#txtname').val("");
                        $('#txtsex').val("");
                        $('#txtage').val("");
                        $('#txterr').val('Record Inserted');
                        $progressbar.css('width', '100%');
                    }
                },
                error: function(data){
                    alert("Something went wrong !");
                });
            });
        });
    });
</script>

Open in new window


With this jQuery plugin : https://github.com/likerRr/jq-ajax-progress
<script> 
    $(document).ready(function(){
        var $progressbar = $("#progressbar");
        $progressbar.show();
        var updateProgressBar = function(evt) {
            if(evt.lengthComputable) {
                var percent = (evt.loaded*100)/evt.total;
                $(function(){
                    $progressbar.css('width', percent.toFixed(1) + '%');
                }); 
            }
        }
        $('#uploadForm').on('submit', function(e){
            e.preventDefault();
            $.ajax({
                url: "insertdata.php",
                type: "POST",
                data: new FormData(this),
                contentType: false,
                processData: false,
                success: function(data){
                    console.log(data);
                    if (data == 'T'){
                        $('#txtname').val("");
                        $('#txtsex').val("");
                        $('#txtage').val("");
                        $('#txterr').val('Record Inserted');
                        $progressbar.css('width', '100%');
                    }
                },
                error: function(data){
                    alert("Something went wrong !");
                });
            });
        }).uploadProgress(updateProgressBar).upload(updateProgressBar);
    });
</script>

Open in new window


/*
 * jQuery Ajax Progress - Lightweight jQuery plugin that adds support of `progress` and `uploadProgress` promises to $.ajax()
 * Copyright (c) 2015 Alexey Lizurchik <al.lizurchik@gmail.com> (http://likerrr.ru)
 * Licensed under the MIT license
 * http://likerrr.mit-license.org/
 */

(function(factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['jquery'], factory);
  } else if (typeof exports === 'object') {
    // Node/CommonJS
    module.exports = factory(require('jquery'));
  } else {
    // Browser globals
    factory(jQuery);
  }
}(function($) {
  var $originalAjax = $.ajax.bind($);

  $.ajax = function (url, options) {
    if (typeof url === 'object') {
      options = url;
      url = undefined;
    }
    options = options || {};

    // Instantiate our own.
    var xmlHttpReq;

    if (!options.xhr) {
      xmlHttpReq = $.ajaxSettings.xhr();
    } else {
      xmlHttpReq = options.xhr();
    }

    // Make it use our own.
    options.xhr = function () {
      return xmlHttpReq;
    };

    var chunking = options.chunking || $.ajaxSettings.chunking;

    // this line looks strange, but without it chrome doesn't catch `progress` event on uploading. Seems like engine bug
    xmlHttpReq.upload.onprogress = null;

    var $newPromise = $originalAjax(url, options);

    // Extend our own.
    $newPromise.progress = function (handler) {
      // Download progress
      var lastChunkLen = 0;
      xmlHttpReq.addEventListener('progress', function (e) {
        var params = [e],
          chunk = '';

        if (this.readyState == 3 && chunking) {
          chunk = this.responseText.substr(lastChunkLen);
          lastChunkLen = this.responseText.length;
          params.push(chunk);
        }
        handler.apply(this, params);
      }, false);

      return this;
    };

    $newPromise.uploadProgress = function(handler) {
      // Upload progress
      if (xmlHttpReq.upload) {
        xmlHttpReq.upload.addEventListener('progress', function (e) {
          handler.apply(this, [e]);
        }, false);
      }

      return this;
    };

    return $newPromise;
  };
}));

Open in new window

2
 

Author Comment

by:Ratan Shastri
ID: 41879901
Thanks it really helped me a lot, can u please provide me a link from where can I study more about this.
0
 
LVL 82

Accepted Solution

by:
leakim971 earned 2000 total points
ID: 41879991
1
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 41880315
Here is the demonstration link for the article about progress bars:
https://iconoun.com/demo/jquery_progress_bar.php

See also:
My Favorite Lazy Alternative in the article.  This may be enough for essentially instantaneous activities like a database INSERT query.
https://v.cdn.vine.co/w/ccf87cd9-assets/images/loading_black.gif
1

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article shows the steps required to install WordPress on Azure. Web Apps, Mobile Apps, API Apps, or Functions, in Azure all these run in an App Service plan. WordPress is no exception and requires an App Service Plan and Database to install
Containers like Docker and Rocket are getting more popular every day. In my conversations with customers, they consistently ask what containers are and how they can use them in their environment. If you’re as curious as most people, read on. . .
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…
Suggested Courses

609 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question