- File Upload with Progress Bar using jQuery Ajax and PHP
- File Upload Form with Progress Bar
- Upload File to Server using PHP
- Conclusion
- Saved searches
- Use saved searches to filter your results more quickly
- TheBrockEllis/jQuery-and-PHP-Progress-Bar
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- jQuery Progress Bar for PHP AJAX File Upload
- File Upload Form showing Progress Bar
- jQuery Form Submit
- Popular Articles
File Upload with Progress Bar using jQuery Ajax and PHP
The file upload feature is the most used functionality for the dynamic web application. The file upload functionality can be easily implemented using PHP. Generally, the page is refreshed when you upload file using PHP. To make this file upload user-friendly, jQuery and Ajax can be used to upload files/images without page refresh.
While the file is uploading to the server, the web page stays on the loading state. It’s very difficult for the user to track the upload progress. Progress Bar is very useful to overcome this issue by showing the upload progress in a human-readable format. A progress bar is a graphical element that visualizes the progression of an operation. Generally, a progress bar is used to show progress representation in percentage format for upload, download, or installation. In this tutorial, we will show you how to upload file in PHP and make a progress bar using jQuery and Ajax.
In the example ajax progress bar with percentage script, we will implement the following functionality.
- HTML form to select file.
- Display progress bar when the upload is on the process using jquery.
- Add upload completion percentage to the progress bar real-time using Ajax.
- Upload file to server using PHP.
Before getting started to integrate file upload with progress bar, take a look at the file structure.
php_file_upload_with_progress_bar_jquery/ ├── index.html ├── upload.php ├── uploads/ ├── js/ │ └── jquery.min.js ├── css/ │ └── style.css └── images/
File Upload Form with Progress Bar
The index.html file handles the file selection and live upload progress display operations.
File Upload Form:
1. Create an HTML form with a file input field and a submit button.
- The < form >tag must contain the enctype=»multipart/form-data» attributes.
- The < input >tag must contain type=»file» .
form id="uploadForm" enctype="multipart/form-data"> label>Choose File: label> input type="file" name="file" id="fileInput"> input type="submit" name="submit" value="UPLOAD"/> form>
2. Define an HTML element to display the progress bar.
div class="progress"> div class="progress-bar"> div> div>
3. Define an HTML element to display the file upload status.
Ajax File Upload with Progress Bar:
The jQuery and Ajax is used to upload file with a progress bar, so include the jQuery library first.
script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> script>
The following jQuery code sends the selected file data to the server-side script without reloading the page via Ajax.
- On form submission, the selected file data is sent to the server-side script ( upload.php ) using jQuery and Ajax.
- The xhr option of the $.ajax() method is used to track the upload progress.
- The window.XMLHttpRequest() method creates a new XMLHttpRequest object.
- The progress event of XMLHttpRequest upload property indicates the amount of progress made so far.
- The upload progress percentage is attached to the progress bar.
- Based on the response, the upload status is displayed on the webpage.
- The File API is used to get the type of the selected file.
- The MIME type of the selected file is validated and restricts the user to upload only the image (.jpeg/.jpg/.png/.gif) or PDF (.pdf) or MS Word (.doc/.docx) file.
- The includes() method determines whether allowedTypes array contains the selected file type.
script> $(document).ready(function( )< // File upload via Ajax $("#uploadForm").on('submit', function(e)< e.preventDefault(); $.ajax(< xhr: function( ) < var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener("progress", function(evt) < if (evt.lengthComputable) < var percentComplete = ((evt.loaded / evt.total) * 100); $(".progress-bar").width(percentComplete + '%'); $(".progress-bar").html(percentComplete+'%'); > >, false); return xhr; >, type: 'POST', url: 'upload.php', data: new FormData(this), contentType: false, cache: false, processData:false, beforeSend: function( )< $(".progress-bar").width('0%'); $('#uploadStatus').html(' '); >, error:function( )< $('#uploadStatus').html('
File upload failed, please try again.
'); >, success: function(resp)< if(resp == 'ok')< $('#uploadForm')[0].reset(); $('#uploadStatus').html('File has uploaded successfully!
'); >else if(resp == 'err')< $('#uploadStatus').html('Please select a valid file to upload.
'); > > >); >); // File type validation $("#fileInput").change(function( )< var allowedTypes = ['application/pdf', 'application/msword', 'application/vnd.ms-office', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'image/jpeg', 'image/png', 'image/jpg', 'image/gif']; var file = this.files[0]; var fileType = file.type; if(!allowedTypes.includes(fileType))< alert('Please select a valid file (PDF/DOC/DOCX/JPEG/JPG/PNG/GIF).'); $("#fileInput").val(''); return false; > >); >); script>Upload File to Server using PHP
The upload.php file is called by the Ajax request to handles the file upload process with PHP.
- Retrieve the file information from posted data using the PHP $_FILES method.
- Upload the file to the server using move_uploaded_file() function in PHP.
- Render file upload status that returns to the Ajax success function.
$upload = 'err';
if(!empty($_FILES['file'])) <
// File upload configuration
$targetDir = "uploads/";
$allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg', 'gif');
$fileName = basename($_FILES['file']['name']);
$targetFilePath = $targetDir.$fileName;
// Check whether file type is valid
$fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
if(in_array($fileType, $allowTypes)) <
// Upload file to the server
if(move_uploaded_file($_FILES['file']['tmp_name'], $targetFilePath)) <
$upload = 'ok';
>
>
>
echo $upload;
?>Conclusion
The progress bar provides and user-friendly way of showing the upload completion status in real-time. You can add the jQuery progress bar to file upload and display percentage progress bar while the file is uploading to the server. The progress bar can be added to any type of file upload (image, pdf, doc, docx, audio, video, etc) in PHP. Our example code helps you to easily make the progress bar with percentage for upload, download, and installation operations.
Are you want to get implementation help, or modify or enhance the functionality of this script? Click Here to Submit Service Request
If you have any questions about this script, submit it to our QA community — Ask Question
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
A progress bar created with PHP and jQuery
TheBrockEllis/jQuery-and-PHP-Progress-Bar
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
A progress bar created with PHP and jQuery to give users a visual indicator when long scripts are executing
This progress bar was made out of necessity because we kept dealing with long scripts. We would execute a script that would take > 3 minutes to complete and users would get upset because they weren’t sure if any progress was being made or not. Sometimes they would navigate away from the page and become even more upset, or worse, the script would time out.
This script uses a PHP object to control the PHP code for the progress bar. There is a simple CSS file for the style which looks amazing in webkit browsers and gracefully degrades in older browsers. The .htaccess file is needed to disable gzipping which can cause the buffers to fail and nothing be echoed to the browser.
The original code for this progress bar is credited to ______.
This work is credited to Brock Ellis and Brent Zuch of Sycamore Leaf Solutions.
About
A progress bar created with PHP and jQuery
jQuery Progress Bar for PHP AJAX File Upload
This tutorial will display a progress bar during the AJAX file upload process using jQuery. We are using jQuery form library and functions $(form).ajaxSubmit() update to submit form data to the PHP page.
After progressing image upload, we show the preview to the target selector.
File Upload Form showing Progress Bar
In this form, we have a file input field and a progress bar to show the file upload progress.
Initially, the progress bar width is set to 0, which will gradually increase based on the progress completed.
jQuery Progress bar for PHP AJAX File Upload #uploadForm label < margin: 2px; font-size: 1em; >#progress-bar < background-color: #12CC1A; color: #FFFFFF; width: 0%; -webkit-transition: width .3s; -moz-transition: width .3s; transition: width .3s; border-radius: 5px; >#targetLayerjQuery Form Submit
$(form).ajaxSubmit() contains set of options to track the progress of the AJAX call. jQuery uploadProgress updates the progress bar status with the currently completed uploading progress. The script is,
$(document).ready(function() < $('#uploadForm').submit(function(e) < if ($('#userImage').val()) < e.preventDefault(); $('#loader-icon').show(); $(this).ajaxSubmit(< target: '#targetLayer', beforeSubmit: function() < $("#progress-bar").width('0%'); >, uploadProgress: function(event, position, total, percentComplete) < $("#progress-bar").width(percentComplete + '%'); $("#progress-bar").html('
PHP file upload code is the same as we have seen for single and multiple image uploads using jQuery.
This code returns the image HTML with the uploaded image source. It will show the preview on the browser using the callback script.
Popular Articles
- PHP
- jQuery
- jQuery Tutorials
- jQuery Bootstrap
- jQuery Effects
- jQuery Animation
- jQuery Menu
- jQuery AJAX Form
- jQuery Form Validation
- jQuery Contact Form
- jQuery File Upload
- PHP AJAX Image Upload
- PHP Upload Multiple Files via AJAX using jQuery
- Add Delete Image via jQuery AJAX
- jQuery Drag and Drop Image Upload
- jQuery Progress Bar for PHP AJAX File Upload
- jQuery Ajax Image Resize with Aspect Ratio
I’m currently available for freelance work.
- Simple PHP Shopping Cart
- Stripe Payment Gateway Integration using PHP
- User Registration in PHP with Login: Form with MySQL and Code Download
- PHP Contact Form
- How to Create Dynamic Stacked Bar, Doughnut and Pie charts in PHP with Chart.js
“ The whole experience was extremely professional. We agreed on the requirements and scope of work quickly. The price was fair. Vincy promised quick turn-around and delivered on time . ”
Michael Goldstein, HHG Development Associates LLC, USA