Webpack + ajaxForm
garbinmarcelo opened this issue · 2 comments
Hi, I've been having a problem for a while and I couldn't figure out what it might be.
I'm using Laravel 6 with webpack, I have a script with ajaxForm that I use to send the form with a file and sometimes without. It turns out that when I use the form to register it runs normally, and when I do an update it ends up being sent 2 times.
If I place the script directly on the blade without using require ('script-name'); via webpack, it works normally, without repetition of sending.
Any idea what it might be or what I can do to find out what's causing it?
Edit.:
my code:
$(document).ready(function(){
let btn_submit = $(".btn-submit"),
btn_submit_txt = btn_submit.html(),
xhr = null,
UpCancelado = false;
$("form[upload-ajax]").each(function(){
let form = $(this),
form_action = form.attr('action'),
form_method = form.attr('method'),
_method = form.find(':hidden[name=_method]').val() || null;
// Verifica se submit possui btn-submit
// Se sim, remove a classe
if(form.length > 0 && btn_submit.length > 0)
btn_submit.removeClass('btn-submit');
// form ajaxForm
form.ajaxForm({
url: form_action,
type: form_method,
dataType: 'json',
beforeSubmit: function(){
console.log('beforeSubmit');
if(form.valid()){
helpers.btnDisabled(btn_submit, btn_submit.text(), 0);
progressbar();
return true;
}
return false;
},
beforeSend: function(jqXHR, settings){
xhr = jqXHR;
$("#progressbar #btn-cancelar").prop('disabled', false);
},
uploadProgress: function(event, enviado, total, percentComplete){
progressbar(enviado, total, percentComplete);
if(UpCancelado === true){
xhr.abort();
progressbar(0, 0, 0, false);
setTimeout(function() {
window.location.href = form_action;
}, 1000);
}
},
complete: function(dataJSON, textStatus){
let response = dataJSON.responseJSON;
if(textStatus === 'error'){
console.log('Form Action:', form_action);
console.log('HTTP Code:', dataJSON.status);
console.log('Message Error:', response.message);
console.log('Errors:', JSON.stringify(response.errors));
//
if(_method === 'PATCH')
form_action = form_action + '/editar';
// redirect
setTimeout(function() {
window.location.href = form_action;
}, 1000);
}else{
if(dataJSON.responseJSON){
setTimeout(function(){
window.location.href = response.url;
}, 1000);
}else{
console.log('Erro upload arquivo!');
console.log('Link: ' + form_action);
console.log(dataJSON);
}
//
btn_submit.prop('disabled', false);
btn_submit.html(btn_submit_txt);
}
}
});
});
// Cancelar Upload
$(document).on('click', '#progressbar #btn-cancelar', function(){
if(xhr){
UpCancelado = true;
console.log('Cancelando...');
}
});
});
const progressbar = (enviando = 0, totalArquivo = 0, percentComplete = 0, enviar = true) => {
let id_progressbar = 'progressbar',
total = helpers.bytesToSize(totalArquivo),
enviado = helpers.bytesToSize(enviando),
progressbar = $(`#${id_progressbar}`),
msg_size = (totalArquivo > 0)? `Enviando ${enviado} de ${total}` : 'Preparando envio...',
template = `<div id="${id_progressbar}" class="w-100 h-100 position-fixed d-flex flex-column justify-content-center align-content-center align-items-center">
<div class="progress">
<div class="progress-bar progress-bar-striped progress-bar-animated bg-success" role="progressbar" style="width: 0%">0%</div>
</div>
<small class="size m-0 mt-2"></small>
<button type="button" id="btn-cancelar" class="btn btn-danger btn-sm mt-3" disabled="disabled">Cancelar</button>
</div>`;
// Verificar se ja tem div progressbar
// Se não, adiciona layout após body
if(!progressbar.length){
$('body').prepend(template);
progressbar = $(`#${id_progressbar}`);
}
// Se o envio foi cancelado atualiza progress-bar
if(!enviar){
progressbar.find('.progress-bar').css('width', '100%').removeClass('bg-success').addClass('bg-danger').html('Cancelando...');
progressbar.find('.size').remove();
progressbar.find('#btn-cancelar').remove();
}else{
// Atualiza valores progress-bar
progressbar.find('.progress-bar').css('width', percentComplete + '%').html(percentComplete + '%');
progressbar.find('.size').html(msg_size);
}
// Escode btn cancelar
if(percentComplete === 100){
$("#progressbar #btn-cancelar").hide('fast');
}
console.log('Total: ' + total + ' / ' + enviado + ' => ' + percentComplete + '%');
};
Today I discovered something, when I have the validation code of the commented form the problem of sending 2 times is not presented. So I think it has something to do with the https://github.com/proengsoft/laravel-jsvalidation package. I'm going to take another look, this is already a step forward.
I will close this issue, as it seems to me that this is an error with the other package (laravel-jsvalidation).