简体   繁体   English

提交表单后,如何在 ajax 错误消息中获取在服务器端处理的错误?

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

The question问题

I have these files:我有这些文件:

  • upload.php -> has the form and ajax upload.php -> 有表格和 ajax
  • uploadSubmit.php -> sends the data to video.class.php uploadSubmit.php -> 将数据发送到 video.class.php
  • video.class.php -> handles the upload, adds it to the database and handles errors video.class.php -> 处理上传,将其添加到数据库并处理错误

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?如何获取else语句中的错误以传输回 upload.php 并在不刷新页面表单的情况下显示在 div 中?

The code:编码:

upload.php上传.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

<?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视频.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'];
    }
}
?>

I managed to figure it out mostly by changing the Javascript to this:我主要通过将 Javascript 更改为此来解决这个问题:

<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.之后,我将 class 中的所有return更改为echo显,并且它起作用了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 AJAX 提交后如何将验证错误回显到我的表单中? - How do I echo the validation errors to my form after submitting with AJAX? 提交表单后如何显示自定义消息? - how do i display a custom message after submitting a form? 在php中提交表单后如何显示错误消息? - How can I display the error message after submitting the form in php? AJAX jQuery表单提交错误消息 - AJAX jquery form submitting an error message 为什么在WP中提交Ajax联系人表单时出现“ Post” 404错误 - Why do I get a “Post” 404 error when submitting an ajax contact form in WP 使用PHP在页面上提交表单后如何返回消息? - How do I return a message after submitting a form on my page with PHP? 表单提交后如何在不同的php文件处理的html表单下显示成功消息 - How to show success message below html form after form submit which is being handled by different php file 异步提交表单时如何显示php错误消息? - How do I show php error message when I'm submitting the form asynchronously? 提交联系表后如何在同一页面获得成功信息? - 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?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM