AJAX File Upload using PHP, jQuery

Introduction

I will show you how to upload a file using PHP, AJAX and jQuery without page refresh. This file upload tutorial example is very helpful to implement the upload functionality.

In this example the file is selected using the browse button and file is uploaded to the uploads directory. PHP script stores the file into the specified location and returns response as a success or failure message from the PHP script. As a validation step I have checked if end users have selected a file for uploading or not.

Related Posts:

Prerequisites

PHP 7.0.15 – 7.4.3, Apache 2.4, jQuery 1.12 – 3.5

Implementation Steps

  1. Include jQuery library.
  2. HTML page with upload field.
  3. jQuery Ajax code.
  4. PHP script to store the file.

Adding jQuery Library

Include jQuery library into <head/> section of the HTML page:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

Or

<script src="https://code.jquery.com/jquery-3.5.1.min.js" crossorigin="anonymous"></script>

HTML – File Input

Put the below upload field inside <body/> tag in HTML page. As I am going to upload file using AJAX technique so you don’t need HTML <form> element.

<h1>Single File Upload Example using PHP</h1>
<p id="msg"></p>
<input type="file" id="file" name="file" />
<button id="upload">Upload</button>

File Upload Handling – AJAX jQuery

Add below jQuery, AJAX code immediate after the jQuery library inside <head/> section of the HTML page.

I call the server side PHP script using AJAX technique and show message accordingly whether success or failure.

<script type="text/javascript">
	$(document).ready(function (e) {
		$('#upload').on('click', function () {
			var file_data = $('#file').prop('files')[0];
			var form_data = new FormData();
			form_data.append('file', file_data);
			$.ajax({
				url: 'upload.php', // point to server-side PHP script 
				dataType: 'text', // what to expect back from the PHP script
				cache: false,
				contentType: false,
				processData: false,
				data: form_data,
				type: 'post',
				success: function (response) {
					$('#msg').html(response); // display success response from the PHP script
				},
				error: function (response) {
					$('#msg').html(response); // display error response from the PHP script
				}
			});
		});
	});
</script>

File Upload Handling – PHP

Create upload.php file with below source code. I first check if file was selected for uploading. If not selected then show an error.

Next I check if there is any error while uploading file then show errors.

Then I check if file already exists in the uploads directory then I show message – file already exists. Otherwise I upload the file into uploads directory under project directory.

<?php
	if (isset($_FILES['file']['name'])) {
		if (0 < $_FILES['file']['error']) {
			echo '<span style="color:red;">Error during file upload ' . $_FILES['file']['error'] . '</span>';
		} else {
			if (file_exists('uploads/' . $_FILES['file']['name'])) {
				echo '<span style="color:red;">File already exists at uploads/' . $_FILES['file']['name'] . '</span>';
			} else {
				move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
				echo '<span style="color:green;">File successfully uploaded to uploads/' . $_FILES['file']['name'] . '</span>';
			}
		}
	} else {
		echo '<span style="color:red;">Please choose a file</span>';
	}
	echo nl2br("\n");
?>

Testing the Application

Now if you run the above file by hitting URL http://localhost/php-ajax-single-file-upload/ajax_file_upload.php then you will see below output in the browser:

ajax file upload using php jquery

If you try to upload file without selecting any file then you would see error message Please choose a file.

ajax file upload using php jquery

If the file successfully uploaded then you will see success message File successfully uploaded : uploads/<some-file-name>.

ajax file upload using php jquery

If the file you are trying to upload already exists then you will see a message File already exists : uploads/<some-file-name>.

Hope you have got an idea how to upload file using PHP, AJAX and jQuery.

Source Code

Download

3 thoughts on “AJAX File Upload using PHP, jQuery

  1. Thanks for below code
    var file_data = $(‘#file’).prop(‘files’)[0];
    var form_data = new FormData();
    form_data.append(‘file’, file_data);

Leave a Reply

Your email address will not be published. Required fields are marked *