Menu

Ajax Image Upload with Form Data using jQuery, PHP and MySQL

Ajax Image Upload with Form Data using jQuery, PHP and MySQL

Uploading Image from client to server is one of the most popular feature of any web application. jQuery and Ajax can be used to upload image 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.

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.


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

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.

include "include/constants.php";
include('templates/header.php');
?>


Ajax Image Upload with Form Data using jQuery, PHP and MySQL

























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.



Step 5: Upload File & Insert Form Data (action.php and Upload.php)

  • Upload File action.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)



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.

Demo  [sociallocker] Download[/sociallocker]

Ads middle content1

Ads middle content2