Upload file using ajax and jquery

Uploading a file using form is a simple and easy process, you just have to add enctype=”multipart/form-data” in the form tag. Sometimes, you need to upload data using ajax or jquery rather than refreshing the whole page by submitting the form to another page.

The below script demonstrates how to upload form data (especially a file) using ajax and jquery.

Step 1:
Create a folder (upload_ajax_file), create a file (index.php) in that folder and paste the code:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>Ajax File Upload</title>
<script type=”text/javascript” src=”http://code.jquery.com/jquery-latest.js”></script>
<form id=”form” method=”post” action=”test.php” enctype=”multipart/form-data”>
<input type=”file” name=”file” id=”file” />
<input type=”submit” />

<script type=”text/javascript”>
$(“#form”).submit(function(event) {
url: “upload.php”,
type: “POST”,
data: new FormData(this),
contentType: false,

Step 2: create another file (upload.php), where you post the data through ajax and paste the code:

$file = $_FILES[‘file’][‘name’];
//you can also add the file name is database here

echo “File Uploaded”;
} else
echo “Sorry, Please try again”;

This is the basic script for uploading a file using ajax. If you have any further question or suggestion, please feel free to contact by writing in comment box below.