We can send the file to the server using the JQuery Ajax method. And we also preview image file before uploading on the server.
Lets upload file using ajax JQuery.
Files & Folder
- Create a root folder with any name.
- In your main folder create an index.html file.
- ajax [Folder]
- action.ajax.php
- Database.php
- config.php
- CSS [Folder]
- uploads [Folder]
Step 1
In your main file include bootstrap lib.
Note I am using CDN to include Bootstrap and JQuery.
First, we need a form and a container for a preview image. Create a file name index.html and paste the below code in it.
The below snippet is the Bootstrap 4 code. You can change as per your need.
<div class="container">
<div class="ml-2 col-sm-4">
<div id="msg"></div>
<form method="post" id="image-form" enctype="multipart/form-data" onSubmit="return false;">
<div class="form-group">
<input type="file" name="file" class="file">
<div class="input-group my-3">
<input type="text" class="form-control" disabled placeholder="Upload File" id="file">
<div class="input-group-append">
<button type="button" class="browse btn btn-primary">Browse...</button>
</div>
</div>
</div>
<div class="form-group">
<img src="https://placehold.it/80x80" id="preview" class="img-thumbnail">
</div>
<div class="form-group">
<input type="submit" name="submit" value="Upload" class="btn btn-danger">
</div>
</form>
</div>
</div>
Step 2
Now we need to hide the default browse button using CSS. Open the CSS folder and create style.css file and paste the below code in it.
.file {
visibility: hidden;
position: absolute;
}
Step 3
Now we need to JavaScript code to handle browse button default functionality and preview image. Past below code at the bottom of the index.html page just before </body> tag.
$(document).on("click", ".browse", function() {
var file = $(this)
.parent()
.parent()
.parent()
.find(".file");
file.trigger("click");
});
$('input[type="file"]').change(function(e) {
var fileName = e.target.files[0].name;
$("#file").val(fileName);
var reader = new FileReader();
reader.onload = function(e) {
// get loaded data and render thumbnail.
document.getElementById("preview").src = e.target.result;
};
// read the image file as a data URL.
reader.readAsDataURL(this.files[0]);
});
Now we write a code to send ajax request and upload file on the server. I am going to use PHP to upload the file on a server. move_uploaded_file a simple PHP function to upload file.
Step 4
Send ajax request with the file is very simple.
$(document).ready(function(e) {
$("#image-form").on("submit", function() {
$("#msg").html('<div class="alert alert-info"><i class="fa fa-spin fa-spinner"></i> Please wait...!</div>');
$.ajax({
type: "POST",
url: "ajax/action.ajax.php",
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function(data) {
if (data == 1 || parseInt(data) == 1) {
$("#msg").html(
'<div class="alert alert-success"><i class="fa fa-thumbs-up"></i> Data updated successfully.</div>'
);
} else {
$("#msg").html(
'<div class="alert alert-info"><i class="fa fa-exclamation-triangle"></i> Extension not good only try with <strong>GIF, JPG, PNG, JPEG</strong>.</div>'
);
}
},
error: function(data) {
$("#msg").html(
'<div class="alert alert-danger"><i class="fa fa-exclamation-triangle"></i> There is some thing wrong.</div>'
);
}
});
});
});
Step 5
Before going to write PHP code you need to create a new table where you want to save the uploaded image. In this example, I create table with the name of images. Paste below code into your MySql Server for table creation.
--
-- Table structure for table `images`
--
CREATE TABLE `images` (
`id` int(11) NOT NULL,
`img_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`img_order` int(5) NOT NULL DEFAULT '0',
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`status` enum('1','0') CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '1'
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `images`
--
ALTER TABLE `images`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `images`
--
ALTER TABLE `images`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;
Step 6
Create a new file with a name of action.ajax.php in ajax folder and paste the below code.
Before that create the config.php file and create a Database.php file in ajax folder. Now open Database.php file and paste code from here. Or you can download a file from here.
<?php
include_once('config.php');
$file = $_FILES['file']['name'];
$file_image = '';
if($_FILES['file']['name']!=""){
extract($_REQUEST);
$db->delete('images',array('img_order'=>555));
$infoExt = getimagesize($_FILES['file']['tmp_name']);
if(strtolower($infoExt['mime']) == 'image/gif' || strtolower($infoExt['mime']) == 'image/jpeg' || strtolower($infoExt['mime']) == 'image/jpg' || strtolower($infoExt['mime']) == 'image/png'){
$file = preg_replace('/\\s+/', '-', time().$file);
$path = '../uploads/'.$file;
move_uploaded_file($_FILES['file']['tmp_name'],$path);
$data = array(
'img_name'=>$file,
'img_order'=>555
);
$insert = $db->insert('images',$data);
if($insert){ echo 1; } else { echo 0; }
}else{
echo 2;
}
}
?>