upload files using ajax

How to upload files using ajax in php ?

Trying to upload files using ajax? But don’t know how to do it. Here, i will give you complete documentation that how you can upload files using ajax in PHP.
First of all, there will be some requirements before start creating an awesome ajax script in PHP.


  • PHP

Make sure that you have PHP and MYSQL in running state. You can also download xampp or wamp if you are working on localhost.
Resources used in this script

  • HTML
  • CSS
  • PNOTIFY ( JQUERY LIBRARY (just to make the script beautiful. It’s not necessary )
  • AJAX
  • PHP

I have used all the technologies above in order to build this script but some of these are not necessary. So, don’t be confused by seeing all these technologies. I will teach you step by step that how to upload files using ajax.

Create Layout

Let’s start by creating a layout first. I have used bootstrap in order to create a page. You can use simply HTML and CSS. It’s up to you. Here is the code for the layout.

<!DOCTYPE html>
<html lang="en">
	<meta charset="UTF-8">
	<title>Ajax File Upload</title>
	<link rel="stylesheet" href="pnotify/pnotify.css">

		<!-- Latest compiled and minified CSS -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

	<!-- Optional theme -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

	<!-- Latest compiled and minified JavaScript -->
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

	<link rel="stylesheet" href="style.css">


	<!-- It's an animated gif. You can download the resources at the end of the article -->

	<div id="pageloader">
   		<img src="25.gif" alt="processing..." />

<div class="container">
		<div class="form">
			<h1>Upload File using Ajax</h1>

		<form id="ajaxUpload" method="post" enctype="multipart/form-data">

			<img id="image" src="img.jpg" style="width: 50%" alt=""><br><br>
			<input id="file" type="file" name="file" required><br>

			<input style="width: 50%" type="submit" value="Upload" name="submit" class="btn btn-primary">





<script src="pnotify/pnotify.js"></script>


To Style your layout. Create a new file with name style.css and put this code.

  background: #212F3D;

  background: white;
  width: 50%;
  margin-top: 150px;
  padding: 20px;

  background: rgba( 255, 255, 255, 0.8 );
  display: none;
  height: 100%;
  position: fixed;
  width: 100%;
  z-index: 9999;

#pageloader img
  left: 50%;
  margin-left: -32px;
  margin-top: -32px;
  position: absolute;
  top: 50%;

Implement jQuery

Let’s implement jQuery now in order to send a request to an ajax file. So, here is the code for jQuery that you can implement in your code.

		$("#ajaxUpload").submit(function(e) {


		var formData = new FormData($("#ajaxUpload")[0]);

    function() {

    url: "ajaxUpload.php",
    type: "POST",
    data : formData,
    processData: false,
    contentType: false,
    beforeSend: function() {

    success: function(data){


    	   $("#image").attr("src", "uploads/" + data);

    	  new PNotify({
				title: 'Congratulations',
				text: 'You have successfully uploaded your Image',
				type: 'custom',
				addclass: 'notification-success',
				icon: 'fa fa-check'

    error: function(xhr, ajaxOptions, thrownError) {
       console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);

 }, 1000);



Make sure that you have mentioned the “id” in your form tag. As that will be used in jQuery in order to make the script in working state.

Create a database

If you want to save your image in the database for later use. So, you can create your database by simply going into PHPMyAdmin and there you can create your database.
After creating a database, you can simply click on the SQL tab on the PHPMyAdmin and simply put this code and it will automatically create a table for you.

CREATE TABLE `ajaxupload` (
  `id` int(10) NOT NULL,
  `image` varchar(255) NOT NULL

After successfully creating a database, the next step is to configure it.

Configure database

To configure your database, you can simply create a db.php and put this code in it. Don’t forget to change the database name.

	$db = mysqli_connect("localhost","root","","solvetechy");

Now, the connection to the database is completed. Let’s move to the ajax file.

Creating an ajax File

In the ajax file, you will receive the data coming from the PHP File. You will receive the data in POST format and you can manipulate the ajax file and add more validations as per your need. Here is the example of my ajax file that I have used in order to create the script.


$data = array();
    //check with your logic
    if (isset($_FILES)) {
        $error = false;
        $files = array();

        $rand = rand();

        $uploaddir = 'uploads/' ;
        foreach ($_FILES as $file) {
            if (move_uploaded_file($file['tmp_name'], $uploaddir . $rand  . basename( $file['name']))) {
                $files[] = $uploaddir . $file['name'];
                $file_name = $rand . $file['name'];

             $insert = "INSERT into ajaxupload (image) VALUES ('$file_name')";    


             echo $file_name; 


            } else {
                $error = true;
        $data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
    } else {
        $data = array('success' => 'NO FILES ARE SENT','formData' => $_REQUEST);

        You can also print the errors in json format using json_encode($data)



Make sure that the ajax file name is same as that you were used in your PHP file.

Note: Create an uploads folder in your script to move the files.

If you have followed all the above steps. Then you are good to go. Let’s test this script and if you are facing any type of issue. You can use my code that I have provided below. It’s free to download for everyone.

Live Demo Download Project

Give a Comment