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”>
<head>
<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>
</head>
<body>
<form id=”form” method=”post” action=”test.php” enctype=”multipart/form-data”>
<input type=”file” name=”file” id=”file” />
<input type=”submit” />
</form>
</body>
</html>

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

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

<?php
$file = $_FILES[‘file’][‘name’];
if(move_uploaded_file($_FILES[‘file’][‘tmp_name’],”files/”.$file)){
//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.