Hello,
I created file upload with ajax, but then i uploading file ajax refresh page and everything goes to database, but I need to upload file without refreshing the page, somewhere is a problem, and i don't see, please help!
My HTML code:
<pre> <div class="panel panel-default">
<div class="panel-body">
<form id="uploadImage" enctype="multipart/form-data">
<div class="form-group">
<label for="darb_fileUpload">Įkelkite savo pabaigtus darbus</label>
<input type="file" name="darb_fileUpload" id="uploadFile">
</div>
<div class="form-group">
<input type="submit" name="submit" value="Įkelti" class="btn btn-info"/>
</div>
</form>
<div class="progress">
<div class="progress-bar"></div>
</div>
<!--
<div id="uploadStatus"></div>
</div>
</div>
AJAX code :
<pre>$(document).ready(function(){
$("#uploadImage").on('#submit', function(e){
e.preventDefault();
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = ((evt.loaded / evt.total) * 100);
$(".progress-bar").width(percentComplete + '%');
$(".progress-bar").html(percentComplete+'%');
}
}, false);
return xhr;
},
type: 'POST',
url: 'add_darb.php',
data: 'darb_fileUpload'(this),
contentType: false,
cache: false,
processData:false,
beforeSend: function(){
$(".progress-bar").width('0%');
$('#uploadStatus').html('<img src="images/loading.gif"/>');
},
error:function(){
$('#uploadStatus').html('<p style="color:#EA4335;">File upload failed, please try again.</p>');
},
success: function(resp){
if(resp == 'ok'){
$('#uploadImage')[0].reset();
$('#uploadStatus').html('<p style="color:#28A74B;">File has uploaded successfully!</p>');
}else if(resp == 'err'){
$('#uploadStatus').html('<p style="color:#EA4335;">Please select a valid file to upload.</p>');
}
}
});
});
$("#uploadFile").change(function(){
var allowedTypes = ['application/pdf', 'application/msword', 'application/vnd.ms-office', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'image/jpeg', 'image/png', 'image/jpg', 'image/gif'];
var file = this.files[0];
var fileType = file.type;
if(!allowedTypes.includes(fileType)){
alert('Please select a valid file (PDF/DOC/DOCX/JPEG/JPG/PNG/GIF).');
$("#uploadFile").val('');
return false;
}
});
});
PHP code:
if (!empty($_FILES)) {
$targetDir = "../uploads/";
$allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg', 'gif');
$fileName = basename($_FILES['darb_fileUpload']['name']);
$targetFilePath = $targetDir.$fileName;
$fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
if (in_array($fileType, $allowTypes)) {
if (move_uploaded_file($_FILES['darb_fileUpload']['tmp_name'], $targetFilePath)) {
$darb_fileUpload = 'ok';
}
}
}
What I have tried:
I have tried a lot of advice online but couldn't resolve this problem.