Redirect to another page if DropzoneJS image uploa

2019-09-12 10:49发布

问题:

I am using dropzoneJS in my form. The form also record user input. Below code shows what I am doing in simple. Everything is working fine but php variable is not getting its value. It is somewhat like this

if (!empty($_FILES)) {
 $imgID = submitData()//This functions upload image and write image url in database and then return ID of the affected row
}

When submit button in form is clicked, redirection is happening but $imgID is not getting its value

Here is the Javascript

Dropzone.options.myAwesomeDropzone = {
 autoProcessQueue: false,
 etc.. etc ..
init: function() {
 var myDropzone = this;
 $("#submit-all").click(function (e) {
   e.preventDefault();
   e.stopPropagation();
   if (myDropzone.files.length) {
    myDropzone.processQueue(); // upload files and submit the form
    } else {
    $('#my-awesome-dropzone').submit(); // submit the form
    }
  });
// Refresh page when all images are uploaded
myDropzone.on("complete", function (file) {
     if (myDropzone.getUploadingFiles().length === 0 && myDropzone.getQueuedFiles().length === 0) {
          var idvar = '<?php $imgID; ?>';
    window.location.replace("/preview.php?id="+ idvar);
    }
  });
 }
}

Suggest me where I am doing wrong. Is there any alternative available.

回答1:

You can send the id back to the browser as response and take it with dropzone on success event like this.

php: (If this file is used to handle other requests a possible structure can be like this)

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' && !empty($_FILES)) 
{
    $imgID = submitData();
    echo $imgID;
}
else
{
    // The rest of your php file shoul go in here.
}

js:

Dropzone.options.myAwesomeDropzone = {

    // .........

    init: function() {
        // ........

        // On success refresh
        this.on("success", function (file) {
            var idvar = $.trim(file.xhr.response);
            window.location.replace("/preview.php?id=" + idvar);
        }
    }
}