Загрузка изображения с DropZone и другими значениями через AJAX, но вызов SweetAlert при отправке данных

У меня есть форма с некоторыми полями (имя, фамилия и изображение профиля), которая выглядит так:

<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 на своем сайте, чтобы иметь дополнительные поля в форме (отсюда):

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-скрипт? К сожалению, я не нашел ни одного полезного примера, который дал бы мне четкий намек на то, как я мог бы решить эту конкретную проблему.


person Fabian    schedule 13.08.2017    source источник


Ответы (1)


У вас не написана логика отправки данных через ajax на сервер (т.е. PHP). При нажатии кнопки отправки вы сообщаете Dropzone.js processQueue(). Но это само по себе не будет отправлять данные на сервер через ajax.

В событии sendingmultiple вам необходимо получить данные формы и назначить их 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;

Затем напишите свою логику загрузки файлов/изображений, а также обновите базу данных опубликованными данными.

Также проверьте, что я написал подробные руководства о том, как загружать изображения с данными формы при нажатии кнопки с использованием DropzoneJS и PHP через ajax.

Загрузка изображения Ajax Использование Dropzone.js с обычными полями формы при нажатии кнопки с использованием PHP

person muni    schedule 05.08.2018