Categories: AjaxjQueryPHP

PHP and Ajax Asynchronous File Upload using jQuery

Introduction:

Live Demo

This tutorial is for beginners, who started working on PHP Project, and wants to add asynchronous file upload feature, so you’re at right place.

What is PHP Asynchronous File Upload?

So you might thinking what is file upload? And how it works?

The answer is here, to upload your file from your local machine to the server (website) is called file upload, it works exactly same as the definition, when we select our file from the browser and click submit, the browser takes file from our local machine and submits it to the server and server do his job to save the file to the defined path.

Here I am going to explain step by step process to create the file upload feature along with the source code of this tutorial so that you can easily download and test on your local machine.

The things you should know before following this tutorial:

  1. PHP
  2. HTML
  3. jQuery
  4. CSS
  5. Bootstrap

So let’s start some coding:

Create PHP Asynchronous File Upload Demo:

Go ahead and create project folder and add new index.html file and use following script:

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>iTech Empires Demo - PHP File upload using jQuery</title>

    <!-- Bootstrap CSS File -->
    <link
      rel="stylesheet"
      type="text/css"
      href="bootstrap-3.3.5-dist/css/bootstrap.css"
    />
  </head>
  <body>
    <!-- Content Section -->
    <div class="container">
      <div class="row">
        <div class="col-md-12">
          <h2>PHP File Upload using jQuery</h2>
        </div>
      </div>
      <div class="row">
        <div class="col-md-6 col-md-offset-0">
          <div class="form-group">
            <form enctype="multipart/form-data">
              <label>Select File to Upload</label>
              <input id="file_to_upload" type="file" class="form-control" />
            </form>
          </div>
          <div class="form-group">
            <button >

Form and Input Field: The basic need to upload file is to have `<form>` with `enctype=”multipart/form-data”`, if you notice the above file I have added form with enctype, next is the `input` field of `file type`, we have this field with the ID “file_to_upload“.

Submit Button: After `</form>` we have Submit button included with `onClick` event along with function call `uploadFile()`, we are going to write this function under script.js file, which is going to handle file upload operation.

Create script.js file:

Let’s create script.js file and add following source code in to it:

script.js:

/*
// Version 1.0
// iTech Empires - jQuery File Upload Script
*/function uploadFile() {
    if ($("#file_to_upload").val() != "") {
        var file_data = $('#file_to_upload').prop('files')[0];
        var form_data = new FormData();

        form_data.append('file', file_data);

        $.ajax({
            url: 'uploadFile.php', // point to server-side PHP script
            dataType: 'text', // what to expect back from the PHP script, if anything
            cache: false,
            contentType: false,
            processData: false,
            data: form_data,
            type: 'post',
            success: function (data) {
                // get server responce here
                alert(data);
                // clear file field
                $("#file_to_upload").val("");
            }
        });
    }
    else {
        alert("Please select file!");
    }
}

So we have our script.js file ready, here we have uploadFile() function is defined, this function is basically to check validation and get the selected file from input field and submit it to the uploadFile.php page asynchronously using ajax.

So now we need to create uploadFile.php, so go ahead and crated this file to the root, and use following source code:

uploadFile.php

<?php

if (0 < $_FILES['file']['error']) {
    echo 'Error: ' . $_FILES['file']['error'] . '<br>';
} else {
    move_uploaded_file($_FILES['file']['tmp_name'], 'files/' . $_FILES['file']['name']);
    echo "File uploaded successfully!!";
}

Just a 10 lines code 🙂 yes this lines is to have our file uploaded to the `files` folder on server, we are using `move_uploaded_file()` function here. if you remember we had send selected file from “file_to_upload” input field.

We are done with the code, find out following tutorial folder structure and complete source code below:

PHP File Upload using jQuery folder structure

Demo Screen:

if your done with all above steps then go ahead and run the code on your server if not you can download the code from the below link as well.

Download Free Source code:

Yogesh Koli

Software engineer & Blogger lives in India, has 6+ years of experience working with the front-end and back-end web app development.

View Comments

  • sir, sorry, but can you kindly please explain to me about getting path string of the uploaded images, and inserting it into the database, i've been working on your tutorial about CRUD operation using Jquery, and i want to implement image for user, but i am stuck, no image uploaded to my server folder and no path record in database. this is what i've tried for the php file:
    if(isset($_POST['username']) && isset($_POST['email'])
    && (isset($_FILES["file"]["type"])){
    $tmp = $_FILES['file']['tmp_name'];
    $Path = "uploads/".$_FILES['file']['name'];
    if(move_uploaded_file($tmp,$Path))
    {
    $query = "INSERT INTO users(username, email, image) VALUES('$username', '$email', '$Path', '')";
    if (!$result = mysql_query($query)) {
    echo"No data Inserted!";
    exit(mysql_error());
    }
    echo "1 Data Added!";
    }
    }
    am i missing something here or perhaps something inside js file, sir?

    • You're asking for specific tutorial or regarding website development ?
      Although I use laravel framework for development, there lot more tutorials coming related to laravel.

Recent Posts

Complete guide of using Laravel 6 Eloquent Subquery Enhancements

Learn How to use laravel frameworks new improved feature called Eloquent Subquery and get example of using Eloquent Subqueries and…

4 weeks ago

3 Useful examples of using Array Map function in PHP – Best Practices

Learn how to use php array map function with easy and essential tutorial to modify arrays in php here I…

4 weeks ago

Working with PHP Array Filter Function – Best Practices

Learn how to use php array filter function with easy and essential tutorial to filter array in php here I…

4 weeks ago

How to add Access Modifiers with Constructor Parameters in TypeScript

Want to know how to refactor your Typescript class, Learn here utilising Typescript of the best and essential feature that…

4 weeks ago

What is Access Modifiers and how to use Access Modifiers in TypeScript ?

What is Access Modifiers in typescript, how to use Access Modifiers, when to use them, what are the advantage of…

1 month ago

Top 10 Super Useful Packages to Improve Laravel applications in 2019

This tutorial provide ultimate list of package those are top 10 on packagist and super useful to optimize your laravel…

1 month ago