Ajax Image Upload with Form Data using jQuery, PHP and MySQL
Uploading Image from client to server is one of the most popular features of any web application. jQuery and Ajax can be used to upload images without page refresh. In this tutorial, We have share Ajax Image Upload with Form Data using jQuery, PHP and MySQL.
The FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest. It is primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data. The transmitted data is in the same format that the form’s submit() method would use to send the data if the form’s encoding type were set to multipart/form-data.
Step 1: Create MySQL Database and Table
The following SQL creates a upload_file table in the MySQL database.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php CREATE TABLE `upload_file` ( `id` int(11) NOT NULL, `name` varchar(255) NOT NULL, `file_url` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ALTER TABLE `upload_file` ADD PRIMARY KEY (`id`); ALTER TABLE `upload_file` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1; ?> |
Step 2: Database Configuration (constants.php abd DBConnection.php)
The constants.php file is defined constants.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?php date_default_timezone_set('Asia/Kolkata'); $root = "http://" . $_SERVER['HTTP_HOST']; $root .= str_replace(basename($_SERVER['SCRIPT_NAME']), "", $_SERVER['SCRIPT_NAME']); $constants['base_url'] = $root; define('DB_SERVER', 'localhost'); define('DB_USERNAME', 'root'); define('DB_PASSWORD', ''); define('DB_DATABASE', 'xxxxx_DB'); define('SITE_URL', $constants['base_url']); define('HTTP_BOOTSTRAP_PATH', $constants['base_url'] . 'assets/vendor/'); define('HTTP_CSS_PATH', $constants['base_url'] . 'assets/css/'); define('HTTP_JS_PATH', $constants['base_url'] . 'assets/js/'); // windows path //define('BASH_PATH', 'C:/xampp/htdocs/ajax-file-upload-with-form-data-using-jquery-php-mysql/'); // ubuntu path //define('BASH_PATH', '/var/www/ajax-file-upload-with-form-data-using-jquery-php-mysql/'); // MAC path define('BASH_PATH', '/Applications/XAMPP/htdocs/ajax-file-upload-with-form-data-using-jquery-php-mysql/'); define('ROOT_UPLOAD_PATH', BASH_PATH . 'assets/uploads/'); define('HTTP_UPLOAD_PATH', $constants['base_url'] . 'assets/uploads/'); ?> |
The DBConnection.php file is used to connect the MySQL database
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php include "constants.php"; class DBConnection { private $_con; function __construct(){ $this->_con = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD,DB_DATABASE); if ($this->_con->connect_error) die('Database error -> ' . $this->_con->connect_error); } // return Connection function returnConnection() { return $this->_con; } } ?> |
Step 3: Create File (index.php)
The following code shows the HTML for the image upload form.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php include "include/constants.php"; include('templates/header.php'); ?> <div class="row"> <div class="col-lg-12"> <h2>Ajax Image Upload with Form Data using jQuery, PHP and MySQL</h2> </div> </div> <div class="row"> <div class="col-lg-12"> <form method="post" name="upload_file" id="upload-file" enctype="multipart/form-data"> <div class="input-group mb-3"> <input type="text" name="name" class="form-control input-upl-name"" placeholder="Name"> </div> <div class="input-group mb-3"> <input type="file" name="fileURL" class="form-control input-upl-file"" id="file-url"> </div> <button type="button" name="submit" id="action-upl-file" class="float-right btn btn-primary">Submit</button> </form> <div class="row"> <div class="col-lg-6" id="render-image"> </div> </div> </div> </div> <?php include('templates/footer.php'); ?> |
Step 4: Create File (common.js)
The following code using $ajax() method for send data to php also check the success data or error in data sending.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
<script> jQuery(document).on('click', 'button#action-upl-file', function(e){ e.preventDefault(); var formData = new FormData(); formData.append('name', jQuery('form#upload-file').find('.input-upl-name').val()); formData.append('file_url', jQuery('form#upload-file').find('input#file-url')[0].files[0]); $.ajax({ url: baseurl + 'action.php', type: 'post', data: formData, cache: false, processData: false, contentType: false, dataType:'json', beforeSend: function() { $('button#action-upl-file').button('loading'); }, complete: function () { jQuery('button#action-upl-file').button('reset'); jQuery('form#upload-file')[0].reset(); }, success: function(json) { $('.text-danger').remove(); if (json['error']) { for (i in json['error']) { var element = $('.input-upl-' + i.replace('_', '-')); if ($(element).parent().hasClass('input-group')) { $(element).parent().after('<div class="text-danger" style="font-size: 14px;">' + json['error'][i] + '</div>'); } else { $(element).after('<div class="text-danger" style="font-size: 14px;">' + json['error'][i] + '</div>'); } } } else { jQuery('#render-image').html('<img src="'+json.file_name+'" class="img-thumbnail">'); } } }); }); </script> |
Step 5: Upload File & Insert Form Data (action.php and Upload.php)
- Upload File action.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<?php function __autoload($class) { include "include/$class.php"; } $upl = new Upload(); $name = $_POST['name']; // uploadFile function if(!empty($_FILES["file_url"]["type"])){ $fileName = time().'_'.$_FILES['file_url']['name']; $valid_extensions = array("jpeg", "jpg", "png"); $temporary = explode(".", $_FILES["file_url"]["name"]); $file_extension = end($temporary); if((($_FILES["file_url"]["type"] == "image/png") || ($_FILES["file_url"]["type"] == "image/jpg") || ($_FILES["file_url"]["type"] == "image/jpeg")) && in_array($file_extension, $valid_extensions)) { $sourceUPLPath = $_FILES['file_url']['tmp_name']; $targetUPLPath = ROOT_UPLOAD_PATH.$fileName; if(move_uploaded_file($sourceUPLPath,$targetUPLPath)) { $uploadedFileName = $fileName; } else { $uploadedFileName = ''; } } else { $json['error']['file'] = 'Please choose valid file'; } } else { $json['error']['file'] = 'Please choose image'; } if(empty(trim($name))) { $json['error']['name'] = 'Please enter name'; } if(empty($json['error'])) { $upl->setName($name); $upl->setFileURL($uploadedFileName); $chkStatus = $upl->doSave(); $json['file_name'] = HTTP_UPLOAD_PATH.$uploadedFileName; $json['msg'] = 'success'; } echo json_encode($json); ?> |
- Insert Data (Upload.php)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<?php include "DBConnection.php"; class Upload { protected $db; private $_name; private $_file_url; public function setName($name) { $this->_name = $name; } public function setFileURL($file_url) { $this->_file_url = $file_url; } public function __construct() { $this->db = new DBConnection(); $this->db = $this->db->returnConnection(); } // save function public function doSave() { $query = 'INSERT INTO upload_file SET name="'.$this->_name.'", file_url="'.$this->_file_url.'"'; $result = $this->db->query($query) or die($this->db->error); } } ?> |
You can view the live demo from the Demo link and can download the script from the Download link below.