Following steps are pointed under this process :
1. HTML page with upload field.
2. Include jQuery library.
3. jQuery Ajax code.
4. PHP script to store image.
Git URL :
Ajax Code :
$(“#loading”).hide();
$(‘#fileToUpload’).on(‘change’, function(e) {
e.preventDefault();
var formData = new FormData();
formData.append(‘file_image’, $(‘#wrapper input[type=file]’)[0].files[0]);
var image_data = file_browse(formData, ‘‘);
if (image_data.status == ‘success’) {
$(‘#result’).html(image_data.message);
$(‘#file_image’).val(image_data.web_url);
$(‘#show_image’).show();
$(‘#show_image img’).attr(“src”, image_data.web_url);
} else {
err_d = ‘Image is not Uploaded!’;
$(‘#result’).html(err_d);
}
});
function file_browse(formData, url) {
var result;
$.ajax({
type: ‘post’,
dataType: ‘json’,
data: formData,
enctype: ‘multipart/form-data’,
contentType: false,
cache: false,
processData: false,
async: false,
url: url,
beforeSend: function(xhr) {
$(“#loading”).show();
},
success: function(data) {
$(“#loading”).hide();
result = data;
},
error: function(data) {
result = data;
}
});
return result;
}
PHP code used to store the image :
$save_path = dirname(__FILE__).”/uploads/”;
$actual_url = (isset($_SERVER[‘HTTPS’]) ? “https” : “http”) . “://$_SERVER[HTTP_HOST]”;
$actual_url .= (isset($_SERVER[‘REQUEST_URI’]) ? $_SERVER[‘REQUEST_URI’] : ”);
$actual_url = explode(“/”, $actual_url);
array_pop($actual_url);
$actual_url = implode(“/”, $actual_url).’/uploads/’;
if (!empty($_FILES) && isset($_FILES)) {
$rand = rand();
$image_name = $rand.’_’.$_FILES[‘file_image’][‘name’];
$tmp_image_name = $_FILES[‘file_image’][‘tmp_name’];
$image_type = $_FILES[‘file_image’][‘type’];
$image_size = $_FILES[‘file_image’][‘size’];
$status = move_uploaded_file($tmp_image_name, $save_path.$image_name);
$file_arr = array(‘web_url’ => $actual_url.$image_name, ‘status’ => ‘success’, ‘message’ => ‘Image uploaded successfully’, ‘file_name’ => $image_name);
echo json_encode($file_arr);
exit();
}
JQUERY LIBRARAY:
https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js
HTML CODE:
FILE UPLOAD USING PHP AJAX
Image Upload
Conclusion :
In this blog post we have covered a basic topic of ajax of uploading image using PHP. Hope this might have worked for you to understand the ajax property. Keep reading our other blog posts for more interesting.