I'm building a form to upload images and other data and I want it to return json validation or success response via the ajax success function.
Problem is the php script seems to do some of the if
statements, but then completely ignores the extensions validation statement and the file size validation.
I have a switch/case statement in the AJAX to handle the json response from the php script. the switch/case statement then shows the respective message and then fades out.
note: No errors were found in the console.
Thank you for any help.
AJAX:
$(document).ready(function (e) {
$('.add_business_form').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
dataType: "json",
success:function(response){
switch(response.message){
case 'logo_success':
logoSuccess();
break;
case 'file_is_not_image':
file_is_not_image();
break;
case 'No_file_selected':
No_file_selected();
break;
case 'wrong_logo_extention':
Wrong_extention();
break;
case 'logo_too_big':
logo_too_big();
break;
case 'unknown_error':
unknown_error();
break;
}
},
error: function(data){
}
});
}));
});
jQuery functions(to handle ajax response):
<script>
function logoSuccess(){
$('.response_success').fadeIn('fast').delay(10000).fadeOut('fast');
$('.add_business_form')[0].reset();
}
</script>
<script>
function file_is_not_image(){
$('.file_is_not_image').fadeIn('fast').delay(10000).fadeOut('fast');
}
</script>
<script>
function No_file_selected(){
$('.No_file_selected').fadeIn('fast').delay(10000).fadeOut('fast');
}
</script>
<script>
function logo_too_big(){
$('.logo_too_big').fadeIn('fast').delay(10000).fadeOut('fast');
}
</script>
<script>
function unknown_error(){
$('.unknown_error').fadeIn('fast').delay(10000).fadeOut('fast');
}
</script>
PHP script
if(empty($_FILES['uploaded_img_preview']['name'])){
$response["message"] = 'No_file_selected';
}else{
$imgFile = $_FILES['uploaded_img_preview']['name'];
$tmp_dir = $_FILES['uploaded_img_preview']['tmp_name'];
$imgSize = $_FILES['uploaded_img_preview']['size'];
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION));
$upload_dir = '../images/'; // upload directory
// valid image extensions
$valid_extensions = array('jpg','png','jpeg'); // valid extensions
// rename uploading image
$new_logo_name = rand(1000,1000000).".".$imgExt;
// allow valid image file formats
if(in_array($imgExt, $valid_extensions)){
// Check file size '5MB'
if($imgSize < 500000) {
}
else{
$response["message"] = 'logo_too_big';
}
}
else{
$response["message"] = 'wrong_logo_extention';
}
if (move_uploaded_file($tmp_dir,$upload_dir.$new_logo_name)){
$response["message"] = 'logo_success';
}else{
$response["message"] = 'unknown_error';
}
}
echo json_encode($response);
exit();