I am having a form with one image upload field.
I want to upload image file with ajax and fill up one hidden field in form with returned image name via ajax success BEFORE SUBMITTING MAIN FORM with other input fields like name, email, mobile etc......
Following code I have tried but no luck...
HTML form code :
<label>Upload File:</label>
<input name="userFile" id="userFile" type="file" class="form-control"><br>
<button name="marksheet_upload" id="marksheet_upload" class="btn btn-success">Upload</button>
<label>Image Final Name</label>
<input type="text" class="form-control" id="intern_marksheet_image" name="intern_marksheet_image">
// This above field will be hidden and after image file upload, this value should get via ajax response
<div id="loader-icon" style="display:none;"><img src="images/123.gif"></div>
JAVASCRIPT
<script type="text/javascript">
$(document).ready(function(){
// File upload via Ajax
$("#marksheet_upload").click(function(e) {
var dataimg = new FormData();
var marksheet = $('#userFile')[0].files[0];
//append files
dataimg.append('userFile', marksheet);
e.preventDefault();
$.ajax({
type: 'POST',
url: 'register-file-upload.php',
data: dataimg,
contentType: false,
enctype: 'multipart/form-data',
cache: false,
processData:false,
beforeSend: function(){
$('#loader-icon').show();
},
success: function(response){
if(response.upload == 'ok'){
$('#intern_marksheet_image').val(response.image_name);
$('#loader-icon').html(response.image_error);
}else {
$('#intern_marksheet_image').val('xxx');
$('#loader-icon').html(response.image_error);
}
}
});
});
</script>
PHP ajax url -
register-file-upload.php code :
<?php
function randStrGen601($len){
$result = "";
$chars = "0123456789abcdefghijklmnopqrstuvwxyz";
$charArray = str_split($chars);
for($i = 0; $i < $len; $i++){
$randItem = array_rand($charArray);
$result .= "".$charArray[$randItem];
}
return $result;
}
$error = false;
$imagetypeerror = false;
if (isset($_FILES['userFile'])) {
$avatar1 = $_FILES['userFile'];
$avatarname1 = $_FILES['userFile']['name'];
$avatarsize1 = $_FILES['userFile']['size'];
$minsize1 = 100000; // 100 KB
$maxsize1 = 500000; //500 KB
$acceptable1 = array(
'image/jpeg',
'image/jpg',
'image/png'
);
if(function_exists('finfo_open')){ //(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)
$fileinfo1 = finfo_open(FILEINFO_MIME_TYPE);
if(!empty($avatar1['tmp_name'])){
if (!in_array(finfo_file($fileinfo1, $avatar1['tmp_name']), $acceptable1)) {
$msg = "Marksheet Image is not a valid image, Only 'JPG' & 'PNG' Types Are Allowed";
$error = true;
$imagetypeerror = true;
$data['upload'] = "Err";
$data['image_error'] = $msg;
$data['image_name'] = "";
}
}
}else if(function_exists('mime_content_type')){ //supported (PHP 4 >= 4.3.0, PHP 5)
if (!in_array(mime_content_type($avatar1['tmp_name']), $acceptable1)) {
$msg = "Marksheet Image is not a valid image, Only 'JPG' & 'PNG' Types Are Allowed";
$error = true;
$imagetypeerror = true;
$data['upload'] = "Err";
$data['image_error'] = $msg;
$data['image_name'] = "";
}
}else{
if (!@getimagesize($avatar1['tmp_name'])) { //@ - for hide warning when image not valid
$msg = "Marksheet Image is not a valid image, Only 'JPG' & 'PNG' Types Are Allowed";
$error = true;
$imagetypeerror = true;
$data['upload'] = "Err";
$data['image_error'] = $msg;
$data['image_name'] = "";
}
}
if(!$imagetypeerror){
if( (!isset($avatarname1)) || (empty($avatarname1)) || ($avatarsize1 == 0)) {
$error = true;
$msg= "Please browse and upload the Marksheet Image";
$data['upload'] = "Err";
$data['image_error'] = $msg;
$data['image_name'] = "";
}
if ( (!empty($avatarname1)) && ($avatarsize1 >= $maxsize1)) {
$error = true;
$msg = 'Marksheet Image Size Is Too Large. Image Must Be Less Than 500 KB.';
$data['upload'] = "Err";
$data['image_error'] = $msg;
$data['image_name'] = "";
}
if ( (!empty($avatarname1)) && ($avatarsize1 <= $minsize1)) {
$error = true;
$msg = 'Marksheet Image Size Is Too Small. Image Must Be Greater Than 100 KB.';
$data['upload'] = "Err";
$data['image_error'] = $msg;
$data['image_name'] = "";
}
}
if(!$error){
$targetDir = "uploads/intern/";
$fileName = $_FILES['userFile']['tmp_name'];
$udx = date("YmdHis");
$random2 = randStrGen601(4);
$fileName1 = strtolower($fileName);
$fileName2 = str_replace(" ", "_", $fileName1);
$targetFilePath = $targetDir.$fileName2;
// Upload file to the server
move_uploaded_file($fileName2, $targetFilePath));
$error = false;
$data['upload'] = "ok";
$data['image_error'] = "File Uploaded Successfully";
$data['image_name'] = $fileName2;
}
}
//returm $data;
echo $data;
?>
With this code, I am just getting "XXX" as Image File Name in hidden input field and Loading Image. Image not getting uploaded.
Your original code has a few errors:
The closing braces / brackets are not matching the opening braces / brackets, so add
})to the end of$(document).readyblockRemove the last
)frommove_uploaded_file($fileName2, $targetFilePath));(otherwise the PHP will definitely fail)Use
echo json_encode($data)instead ofecho $datain your PHP script, otherwise we cannot properly return the array dataAdd
dataType: "json",in your ajax block, so that the system evaluates the response of ajax as JSON and returns a JavaScript objectI have slightly changed the filename, filename1 and filename2 assignment lines , since I think they are not quite logical
Please make sure
/uploads/intern/directory is writable so that the file can be uploadedSo, the HTML / JS will be:
and the PHP will be as follows (Note: For the image validation part - I remove them so that you can focus on the file upload part, but you may add it back)
Additional Point (one may try later)
As I have mentioned, The usual UI design is : when the user has selected the file, upload starts (no need to click a button)
In order to do it , change
to