通过AJAX上传带有DropZone和其他值的图像,但在提交数据时调用SweetAlert

时间:2017-08-13 18:48:18

标签: php ajax dropzone.js sweetalert2

我有一个包含一些字段(名字,姓氏和个人资料图片)的表单,如下所示:

<form>
    <div class="row">
        <div class="col-lg-6">
            <label class="control-label">First Name:</label>
            <input class="form-control" type="text" placeholder="Enter first name.." id="firstName">

        </div>
        <div class="form-group col-lg-6">
            <label class="control-label">Last Name:</label>
            <input class="form-control" type="text" placeholder="Enter last name.." id="lastName"> 
        </div>
    </div> <!-- /row -->
    <div class="row">  
        <div class="form-group col-lg-6">
            <label class="control-label">profile picture:</label>
            <div class="dropzone dropzone-previews" id="profilbildDropzone">
                <div class="fallback">
                    <input name="file" type="file" multiple="multiple">
                </div>
            </div>
        </div>
    </div> <!-- /row -->
    <hr />
    <div class="form-action">
        <button type="button" class="btn btn-primary waves-effect waves-light" id="sweet-ajax">Submit Data</button>
    </div>
</form>

当用户点击提交数据时,我调用Sweet-Alert对话框,询问用户是否确定他尝试的操作。如果他点击是,我想通过AJAX将数据提交给PHP脚本,该脚本完成所有其他操作(将图像存储在服务器上,将数据保存在我的数据库中等等):

<script type="text/javascript">
    SweetAlert.prototype.init = function () {
        //Ajax
        $('#sweet-ajax').click(function () {
            swal({
                title: "Sure?", 
                text: "Clicking on yes submits the data!", 
                type: "warning",
                showCancelButton: true,
                closeOnConfirm: false,
                confirmButtonText: "Yes!",
                cancelButtonText: "Cancel",

                showLoaderOnConfirm: true,
                confirmButtonClass: 'btn btn-success',
                cancelButtonClass: 'btn btn-danger m-l-10',
                preConfirm: function(givenData){
                    return new Promise(function(resolve, reject) {
                        setTimeout(function(){
                            inputNameFirst     = document.getElementById("firstName").value;
                            inputNameLast      = document.getElementById("lastName").value;

                            resolve()

                        }, 2000)
                    })
                },
                allowOutsideClick: false
            }).then(function(givenData){
                $.ajax({
                            type: "post",
                            url: "../assets/php/addUser.php",
                            data: {done: "success", fN: inputNameFirst, ln: inputNameLast},
                            dataType: 'JSON',
                            success: function(data) {
                                if(data.status === 'success'){
                                    swal({
                                        type: 'success',
                                        title: 'Good job!',
                                        html: 'all saved now!'
                                    })
                                }else if(data.status === 'error'){
                                    swal({ 
                                        type: 'error',
                                        title: 'Oh No!!',
                                        html: 'Nope sorry, there was an error: <br /><pre>'+ JSON.stringify(data) + '</pre>'
                                    })
                                }
                            }
                        })

            }, function(dismiss) {
                  // dismiss can be 'overlay', 'cancel', 'close', 'esc', 'timer'
                  if (dismiss === 'cancel') {
                    swal(
                      'Got you!',
                      'Nothing changed. Good luck.',
                      'error'
                    )
                  }
              })

            });
     },    
        //init
        $.SweetAlert = new SweetAlert, $.SweetAlert.Constructor = SweetAlert
    }(window.jQuery),

    //initializing
    function ($) {
        "use strict";
        $.SweetAlert.init()
    }(window.jQuery);
</script>

我还在我的网站上设置了DropZone,这样我的表单中也可以包含可选字段(from here):

jQuery(document).ready(function() {

    $("div#profilbildDropzone").dropzone({
        //store images in this directory
        url: "../assets/images/uploads",
        dictDefaultMessage: "Drop image here or click.",
        autoProcessQueue: false,
        maxFiles: 1,
        uploadMultiple: true,
        parallelUploads: 100,

        // The setting up of the dropzone
        init: function() {
            var myDropzone = this;  

            // First change the button to actually tell Dropzone to process the queue.
            this.element.querySelector("button#sweet-ajax").addEventListener("click", function(e) {
                // Make sure that the form isn't actually being sent.
                e.preventDefault();
                e.stopPropagation();
                myDropzone.processQueue();
            });

            // Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
            // of the sending event because uploadMultiple is set to true.
            this.on("sendingmultiple", function() {
                // Gets triggered when the form is actually being sent.
                // Hide the success button or the complete form.
            });
            this.on("successmultiple", function(files, response) {
                // Gets triggered when the files have successfully been sent.
                // Redirect user or notify of success.
            });
            this.on("errormultiple", function(files, response) {
                // Gets triggered when there was an error sending the files.
                // Maybe show form again, and notify user of error
            });
        } 
    });

});

但是我不知道我是如何上传图片或者将它提供给我的PHP脚本的。 在这一行:

this.on("sendingmultiple", function() {
      // Gets triggered when the form is actually being sent.
      // Hide the success button or the complete form.
});

我应该上传图片或者什么?我可以在SWAL函数中调用此函数,还是将数据传递给我的SWAL函数,然后将其发送到PHP脚本? 可悲的是,我还没有找到任何可用的例子,这些例子让我清楚地知道如何解决这个具体问题。

1 个答案:

答案 0 :(得分:0)

您没有被编写为通过ajax向服务器端(即PHP)发送数据的逻辑。单击提交按钮后,您将告诉Dropzone.js processQueue()。但这本身不会通过ajax将数据发布到服务器。

sendmultiple 事件中,您需要获取表单数据并将其分配给 formObject ,然后DropzoneJS会负责将数据沿文件/图像发布到PHP。

init: function() {
    var myDropzone = this;  

    // First change the button to actually tell Dropzone to process the queue.
    this.element.querySelector("button#sweet-ajax").addEventListener("click", function(e) {
        // Make sure that the form isn't actually being sent.
        e.preventDefault();
        e.stopPropagation();
        myDropzone.processQueue();
    });

    // Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
    // of the sending event because uploadMultiple is set to true.
    this.on("sendingmultiple", function() {
        // Append all form inputs to the formData Dropzone will POST
        var data = $form.serializeArray();
        $.each(data, function (key, el) {
            formData.append(el.name, el.value);
        });
    });
}

下一步,在PHP服务器端,像这样获取发布的数据和文件/图像。

<?php 
    //get form data
    echo '<pre>';print_r($_POST);echo '</pre>';
    //get posted files
    echo '<pre>';print_r($_FILES);echo '</pre>';
    exit;

下一步,编写逻辑上载文件/图像,并使用发布的数据更新数据库。

还请检查我是否编写了详细的教程,内容涉及如何通过ajax使用DropzoneJS和PHP在按钮单击时上传带有表单数据的图像。

Ajax Image Upload Using Dropzone.js with Normal Form Fields On Button Click Using PHP