php - How do I get errors which are handled serverside in a ajax error message after submitting a form?
Get the solution ↓↓↓The question
I have these files:
- upload.php -> has the form and ajax
- uploadSubmit.php -> sends the data to video.class.php
- video.class.php -> handles the upload, adds it to the database and handles errors
How do I get the errors which are inelse
statements to transfer back to upload.php and be displayed in a div without the form the page refreshing?
The code:
upload.php
<script type="text/javascript">
$(document).ready(function() {
$('#uploadForm').submit(function(e) {
if($('#video').val()) {
e.preventDefault();
$(this).ajaxSubmit({
target: '#progress-div',
beforeSubmit: function() {
$("#progress-bar").width('0%');
},
uploadProgress: function (event, position, total, percentComplete){
$("#progress-bar").width(percentComplete + '%');
$("#progress-bar").attr('aria-valuenow', percentComplete).css('width', percentComplete + '%');
$("#progress-bar").text(percentComplete + '%');
},
success:function (){
$.ajax({
type: "GET",
url: "getvideourl.php",
dataType: "html",
success: function(response){
$("#responsecontainer").html(response);
$("#result").html('Your video was succesfuly uploaded.' + response);
$("#result").addClass("alert alert-success");
},
error:function (){
$("#responsecontainer").html(response);
$("#result").html('Something went wrong with the upload.');
$("#result").addClass("alert alert-alert");
},
});
},
error:function (){
$("#responsecontainer").html(response);
$("#result").html('Something went wrong with the upload.');
$("#result").addClass("alert alert-alert");
},
resetForm: true
});
return false;
}
});
});
</script>
<div id="result"></div>
<form id="uploadForm" action="uploadSubmit.php" enctype="multipart/form-data" method="POST">
<div class="input-group margin-bottom-sm" style="margin-bottom: 5px;">
<span class="input-group-text"><i class="bi bi-camera-video-fill"></i></i> Select video</span>
<input class="form-control" id="video" type="file" name="video" accept="video/*" placeholder="Video" required/>
</div>
<div class="progress" id="progress-div" style="margin-bottom: 5px;">
<div class="progress-bar" id="progress-bar" role="progressbar" width="0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<div class="input-group margin-bottom-sm" style="margin-bottom: 5px;">
<span class="input-group-text"><i class="bi bi-camera-video-fill"></i></i> Select thumbnail</span>
<input class="form-control" id="thumbnail" type="file" name="thumbnail" accept="image/*" placeholder="Thumbnail" required/>
</div>
<div class="input-group margin-bottom-sm" style="margin-bottom: 5px;">
<span class="input-group-text"><i class="bi bi-chat-right-text-fill"></i></i> Title</span>
<input class="form-control" type="text" name="title" placeholder="Title" required/>
</div>
<label for="description">Description:</label>
<textarea name="description" id="signature"></textarea>
<script>
$('#signature').summernote({
height: 250,
// toolbar
toolbar: [
['font', ['bold', 'italic', 'underline', 'clear']],
['color', ['color']],
['para', ['ul', 'ol', 'paragraph']],
['view', ['fullscreen']],
['help', ['help']]
]
});
</script>
<div class="input-group margin-bottom-sm" style="margin-top: 5px; margin-bottom: 5px;">
<span class="input-group-text"><i class="bi bi-tags-fill"></i></i> Tags</span>
<input class="form-control" type="text" name="tags" placeholder="Separate by comma" />
</div>
<div><input type="submit" id="btnSubmit" value="Submit" class="btnSubmit" /></div>
</form>
uploadsubmit.php
<?php
include'config.php';
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(isset($_FILES) && !empty($_FILES)){
$title = $_POST['title'];
$desc = $_POST['description'];
$tags = $_POST['tags'];
echo $video->upload($_FILES, $title, $desc, $tags);
}
else{
echo $toobig;
}
}
else{
die('<img src="https://i.kym-cdn.com/entries/icons/original/000/028/021/work.jpg" />');
}
?>
video.class.php
<?php
//Upload handler
public function upload($file, $title, $desc, $tags){
global $coreLang;
global $videoMessage;
$file = $_FILES['video'];
if(isset($_FILES['thumbnail'])){
$thumbnail = $_FILES['thumbnail'];
}
else{
$thumbnail = '';
}
if($file['error'] === 0){
$mimeType = mime_content_type($file['tmp_name']);
$fileType = explode('/', $mimeType)[0];
if(is_uploaded_file($file['tmp_name'])){
if ($fileType === 'video'){
$sourcePath = $file['tmp_name'];
$filename = $this->rand->String() . uniqid();
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
$targetPath = "videos/users/" . $filename;
if(move_uploaded_file($sourcePath, $targetPath . '.' . pathinfo($file['name'], PATHINFO_EXTENSION))){
$query = $this->handler->prepare('INSERT INTO videos (u_id, v_filename, v_extension, v_title, v_desc, v_tags) VALUES (:u_id, :v_filename, :v_extension, :v_title, :v_desc, :v_tags)');
try{
$query->execute([
':u_id' => $this->user->getUserId(),
':v_filename' => $filename,
':v_extension' => $extension,
':v_title' => $title,
':v_desc' => $desc,
':v_tags' => $tags,
]);
}catch(PDOException $e){
return $this->errorHandler->dbError();
}
if(!empty($thumbnail)){
$this->uploadThumbnail($thumbnail, $filename);
}
}
else{
return $coreLang['error'];
}
}
else{
$videoMessage['noVideo'];
}
}
else{
return $coreLang['error'];
}
}
elseif($file['error'] === 1){
return $videoMessage['tooBig'];
}
elseif($file['error'] === 4){
return $videoMessage['noFile'];
}
elseif($file['error'] === 7){
return $videoMessage['diskError'];
}
else{
return $coreLang['error'];
}
}
?>
Answer
Solution:
I managed to figure it out mostly by changing the Javascript to this:
<script type="text/javascript">
$(document).ready(function() {
$("#btnSubmit").click(function() {
var formData = new FormData($('#uploadForm')[0]);
$.ajax({
url: "uploadSubmit.php",
type: 'POST',
data: formData,
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
$('#status').html('<b> Uploading -> ' + (Math.round(percentComplete * 100)) + '% </b>');
$("#progress-bar").width(Math.round(percentComplete * 100) + '%');
$("#progress-bar").attr('aria-valuenow', Math.round(percentComplete * 100)).css('width', Math.round(percentComplete * 100) + '%');
$("#progress-bar").text(Math.round(percentComplete * 100) + '%');
}
}, false);
return xhr;
},
success: function(data) {
if (data.includes('!=[]_')) {
$("#result").html(data.substr(5));
$("#result").addClass("alert alert-success");
}
else {
$("#result").html(data);
$("#result").addClass("alert alert-danger");
}
},
error: function(data){
},
cache: false,
contentType: false,
processData: false,
resetForm: true
});
return false;
});
});
</script>
After that I changed allreturn
in the class to anecho
and it worked.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: to enable extensions, verify that they are enabled in your .ini files
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.