Skip to content

Instantly share code, notes, and snippets.

@MohamedLamineAllal
Created November 21, 2018 11:04
Show Gist options
  • Save MohamedLamineAllal/a76310138c96ee838ea859232c08b588 to your computer and use it in GitHub Desktop.
Save MohamedLamineAllal/a76310138c96ee838ea859232c08b588 to your computer and use it in GitHub Desktop.
Dropezonejs complete example (thumbnail preloading, sending a form a long, or form alone, going arround add to dropzone quirk)
var lastLogoUrl = '{{route('storage.companies.logo', ['file' => basename($cmpny->logo)])}}';
{{-- var isLogoUpdated = false; --}}
var updatedData = null;
var oldData = null;
var form = null;
var dataToSend = null;
var dropzoneUpdated = false;
var dropzoneFirstChange = false;
function loadStarterThumbnail(url, mockFile) {
this.emit('addedfile', mockFile);
this.emit('thumbnail', mockFile, url);
this.files.push(mockFile);
// this.files.status = Dropzone.SUCCESS;
// this.removeFile(this.files[0]);
console.log(this.files.status);
}
/*this.options.addedfile.call(this, mockFile); this.options.thumbnail.call(this, mockFile, url); // for ref*/
$(document).ready(function () {
console.log(Dropzone);
var xsrfToken = decodeURIComponent(readCookie('XSRF-TOKEN'));
if (xsrfToken) { // just to test use meta better
console.log('token from cookie');
console.log(xsrfToken);
$.ajaxSetup({
headers: {
'X-XSRF-TOKEN': xsrfToken
}
});
} else {
console.log('token from meta');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
}
form = $(document.getElementById('editCompanyForm'));
console.log('form init = ');
console.log(form);
oldData = formArrayToObject(form.serializeArray());
console.log("old data = ");
console.log(oldData);
$('div#logoDropzone').dropzone({
//url does not has to be written
//if we have wrote action in the form
//tag but i have mentioned here just for convenience sake
url: '{{ route('system.admin.dashboard.companies.edit') }}',
//addRemoveLinks: true,
autoProcessQueue: false, // this is important as you dont want form to be submitted unless you have clicked the submit button
{{-- autoDiscover: false, --}}
paramName: 'logo', // this is optional Like this one will get accessed in php by writing $_FILE['pic'] // if you dont specify it then bydefault it taked 'file' as paramName eg: $_FILE['file']
previewsContainer: '#logoPreview', // we specify on which div id we must show the files
clickable: true, // this tells that the dropzone will not be clickable . we have to do it because v dont want the whole form to be clickable
// maxFiles:1,// to tell it only 1 file max (set that parameter, when exceeded it will trigger maxfilesexceeded event)
thumbnailWidth: 200,
thumbnailHeight: 200,
thumbnailMethod: 'crop',
previewTemplate: '<div class="dz-preview dz-file-preview">\n' +
'<div class="dz-details">\n' +
'<img data-dz-thumbnail /\n>' +
'</div>\n' +
'</div>',
dictDefaultMessage: 'Drag or click',
acceptedFiles: 'image/*',
accept: function(file, done) {
console.log("uploaded");
dropzoneFirstChange = true;
done();
},
success: function (file, response) {
console.log("succcess !!! ::::")
console.dir(file)
console.log('response === ')
console.dir(response)
dropzoneUpdated = false;
// here show an Alert Of success (wow alert)
if (response.redirect) {
window.alertAtEditSuccess();
console.log(response.redirect); console.log(response);
setTimeout(function () {
window.location.href = response.redirect;
}, 1000);
} else {
alert('something went wrong !!! \n\n' + JSON.stringify(response));
}
},
error: function(file, msg){
alert(JSON.stringify(msg));
},
init: function() {
var myDropzone = this;
//now we will submit the form when the button is clicked
{{-- this.on("maxfilesexceeded", function(file) {
this.removeAllFiles();
this.addFile(file);
}); --}}
//loadStarterThumbnail.call(this, lastLogoUrl, {name: 'f', size: 100}); // doesn't work either
loadStarterThumbnail.call(this, lastLogoUrl, {name: ''});
//another way to make sure only one file
this.on('addedfile', function(file) {
dropzoneUpdated = true; // we are saving that it added a file, and so we need to send the new file to the backend (what if it's the same file, well we don't care, may be we think about something later (because i need to explore the api, for the possiblity, and see how to avoid all possible problems (files with same names, overided filesq ..etc)))
if (this.files.length > 1) {
this.removeFile(this.files[0]);
}
});
this.on('sending', function (data, xhr, formData) {
//formData.append('fieldname', 'value');
console.log('====>');
console.dir(formData)
console.dir(data)
var keys = Object.keys(dataToSend);
var name;
var value;
for (var i = 0; i < keys.length; i++){
name = keys[i];
value = dataToSend[keys[i]];
formData.append(name, value);
}
if (!dataToSend.hasOwnProperty('_token')) {
console.log('token didn\'t exist! adding it');
console.log($('meta[name="csrf-token"]').attr('content'));
console.log("-");
console.log(form.get(0).elements['_token']);
formData.append('_token', form.get(0).elements['_token'].value);
}
});
this.on('queuecomplete', function () {
myDropzone.files[0].status = Dropzone.QUEUED;
myDropzone.files[0].progress = 0;
myDropzone.files[0].bytesSent = 0;
{{-- for ref --}}
{{-- var files = myDropzone.files;
for (let i = 0, l = files.length, file; i < l; i++){
file = files[i];
file.status = Dropzone.QUEUED
file.upload.progress = 0;
file.upload.bytesSent = 0;
} --}}
})
// adding our message
var msgcontainer = document.createElement('div');
var msgHighText = document.createElement('div');
var msgSmall = document.createElement('div');
msgcontainer.append(msgHighText, msgSmall);
msgHighText.innerHTML = 'Drag your image here, or click';
msgSmall.innerHTML = 'to add or change';
msgcontainer.className = 'dz-msgContainer';
msgHighText.className = 'dz-msg-high';
msgSmall.className = 'dz-msg-small';
var dzMsg = $('#logoDropzone').find('.dz-default.dz-message');
var span = dzMsg.find('span');
span.show();
span.empty();
dzMsg.append(msgcontainer);
// handle form sumbite
$("#sbmtbtn").on('click',function(e) {
e.preventDefault();
console.log('submit');
dataToSend = {};
// get new form values
var updatedData = form.serializeArray();
// here we will compare the old data to the new one, and check if there is different if yes we update only the right fields
var changementFound = false;
$.each(updatedData, function(key, el) {
if(el.value !== oldData[el.name]) {
dataToSend[el.name] = el.value;
changementFound = true; // just to make sure and not use formData (check formData object later)
}
});
if (changementFound || dropzoneUpdated) {
console.log('change found');
// here go the data that we want to add more then the one on the form
dataToSend['uri'] = window.location.href;
dataToSend['id'] = form.get(0).elements['id'].value;
console.log(dataToSend['id']);
console.log('uri = ', window.location.href);
if (myDropzone.files.length && dropzoneFirstChange) { // if the queue isn't empty
if (dropzoneUpdated) { // logo seem to be updated, let process the queue, and update all the new fields with the logo file in the backend
console.log('myDropzone.processQueue()');
myDropzone.processQueue(); // upload files and submit the form
}
} else { // else if the queue is empty (we submit the form without dropzone doing it)
/* without ajax
var form = addDataToForm('#createCompanyForm', {
'uri': window.location.href
});
$(form).submit(); // just submit the form
console.log('form submited');
*/
console.log('ajax to be sent');
console.log('data = ');
console.log(dataToSend);
console.log('normal ajax sent');
$.ajax({
// The URL for the request
url: "{{ route('system.admin.dashboard.companies.edit') }}",
// The data to send (will be converted to a query string)
data: dataToSend,
// Whether this is a POST or GET request
type: "POST",
// The type of data we expect back
dataType : "json",
})
// Code to run if the request succeeds (is done);
// The response is passed to the function
.done(function( resp ) {
if (resp.redirect) {
window.alertAtEditSuccess();
console.log("done jajax");
console.log(resp.redirect);
console.log(resp);
setTimeout(function () {
window.location.href = resp.redirect;
}, 1000);
} else {
alert('Something went wrong !!');
}
})
// Code to run if the request fails; the raw request and
// status codes are passed to the function
.fail(function( xhr, status, errorThrown ) {
console.error('AJAX FAIL');
console.error(xhr);
alert("Sorry, there was a problem! \n\n" + JSON.stringify(errorThrown));
});
// Code to run regardless of success or failure;
/*.always(function( xhr, status ) {
alert( "The request is complete!" );
});*/
}
} else {
alert('you haven\'t updated anything');
}
// after this, your whole form will get submitted with all the inputs + your files and the php code will remain as usual
//REMEMBER you DON'T have to call ajax or anything by yourself, dropzone will take care of that
});
} // init end
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment