AJAX File Upload using PHP, jQuery

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 defined location and returns response as a success or failure message from the PHP script. As a validation step I have added only to check if you have selected a file for uploading or not.

You may read also  AJAX Multiple Files Upload using PHP, jQuery and AJAX File Upload using Codeigniter, jQuery

Following steps are required in order to upload a file

1.  Include jQuery library.

2.  HTML page with upload field.

3.  jQuery Ajax code.

3.  PHP script to store the file.


Step 1. Include jQuery library into <head/> section of the HTML page

Step 2. Put the below upload field inside <body/> tag in HTML page

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

Step 4. Create upload.php file with below source code

If we combine the steps 1, 2, 3 and 4 then the full source code would be as shown below in a file called file_upload_ajax.php

Now if you run the above file 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”.

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

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.

Thanks for reading.

One Reply to “AJAX File Upload using PHP, jQuery”

Leave a Reply

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