How do I get errors which are handled serverside in a ajax error message after submitting a form?

Tom

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 in else 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>&nbsp;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>&nbsp;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>&nbsp; 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>&nbsp; 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'];
    }
}
?>
Tom

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 all return in the class to an echo and it worked.

Collected from the Internet

Please contact javaer1[email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

how to clear validation errors for mat error after submitting the form

How to get the error message in Controller or Route after handled exception in errorHandler?

How to get the sucess message in the same page after submitting the contact form?

How to get the success message in the same page after submitting the form?

How do I handle errors that are already handled by another error?

How do I get my error message to go away after form validation in react js?

How to show success message below html form after form submit which is being handled by different php file

After submitting 'Contact' message, how do I get it to stay on page and generate a text confirmation?

How to avoid URL $_GET variables after submitting a form with ajax?

display error message after submitting a form

Why do I get the error "[]" when submitting a form?

How to display alert message after submitting form

How do I redirect users after successfully submitting form data?

How can I get the form values to appear in the table after submitting?

How to clean form after submitting ajax?

Form is Submitting Although Error Handled on Blank Fields

Not able to display message after submitting form using ajax

How to get a popup box after submitting a form?

Why I get the "(node:7424) UnhandledPromiseRejectionWarning" message for handled error?

AJAX not submitting the form after validation

How to add message after submitting form? PHP, Wordpress

How to add a success message after submitting Word form?

How do prevent page reload/refresh from submitting ajax called form and get the texts and uploaded file/image?

why do I get preg_replace() error when submitting a post form in Laravel?

How do I get validation errors from a form object in angular?

How Do I make Checkboxes retain their value after submitting the form in Rails

How can I insert a variable into the resulting url parameter string after submitting my GET form?

How can i get data or pass a data from one page to another after submitting a form in reactjs

How do I get an error's body which contains more error message detail using forge-api for nodejs?