Duplicate upload form submission - JS with Formdata

Asked

Viewed 26 times

0

Come on, you guys! I have a problem with Formdata to send files via AJAX using Formdata. I made an image registration that after loading an image, the user can load a second image. However, loading the page, when registering the first image, everything goes well, in the second image, it is sent 2 times, in the third image, 3 times and so on. When you refresh the page, you restart the cycle. I gave as an example this form, but this happens with all the forms I send with this method. It is as if at each sending click, the DOM was duplicated and each "copy" performed the same tasks. I tested it on other browsers, same thing.

Follow the code below.

HTML

<form id="form_banner" method="post" enctype="multipart/form-data">
    <div class="row" id="conteudo">
        <div class="col s12 input-field">
            <div class="config_img_g">
                <div class="arquivo_midia">Novo banner <span>(Formatos jpg ou png com até 2Mb de tamanho)</span>    </div>
                <input type="file" name="banner" accept=".png, .jpg, .jpeg" class="dropify fileSize">
            </div>
        </div>                  
        <div class="col s12 m3">
            <button id="banner_salvar" class="btn btn_l confirma">Cadastrar</button>
        </div>
    </div>
</form>

JS

function banner_Salva(){
    $('#form_banner').submit(function(e){
        e.preventDefault();
        let formData = new FormData(this);
        if($('.dropify-render').html()!=""){ //Se houver alguma imagem, esse objeto é preenchido com uma imagem. Verificação apenas para não enviar o campo vazio.
            $.ajax({
                type:           "POST",
                url:            "https://"+dominio+"/banner-salva",
                cache:          false,
                contentType:    false,
                processData:    false,
                data:           formData,

                beforeSend:function(){
                    $("#modal").html("<h6 class=\"modal_tit\">Guardando as informações...</h6><div class=\"progress\"><div class=\"indeterminate\"></div></div>")
                    $("#modal").modal("open")
                },

                success: function(retorno){
                    if(retorno.trim() != "OK"){
                        $("#modal").modal("close"),
                        Swal.fire({
                            title:  "Ops!",
                            html:   retorno,
                            icon:   "error",
                            confirmButtonText: "OK"
                        })
                    }
                    
                    $("#modal").modal("close")
                    //As próximas linhas tratam a ferramenta dropfy para deixá-lo pronto (limpo/vazio)
                    $(".dropify-preview")           .removeAttr("style", "display-block")
                    $(".dropify-preview")           .attr("style", "none")
                    $(".dropify-render")            .html("")
                    $(".dropify-filename-inner")    .html("")                           
                }       
            })
            
        }else{
            Swal.fire({
                title:  "Ops!",
                html:   "O banner precisa de uma imagem para ser carregado!",
                icon:   "error",
                confirmButtonText: "OK"
            })
        }

    });
}
  • The problem is that you put the $('#form_banner'). Submit inside a function, every time calling the function it creates an event, creates the Submit routine inside the page onload and calls the function by it... ie reverses the thing :-)

  • Fala, Marcelo! That’s exactly what I found! Rsrs... I was restructuring the file to come post the solution... Tenso, viu! Hahaha!!! But thanks anyway, to confirm my observation! Thanks for the tip, buddy!

  • Good... I got a lot of it there... look watch that jquery events are created to each request, even within other events an option that you can study is $(obj). off it turns off the events of the object, but it is good to read about it to apply in the right way, good luck ai.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.