optional input file reloads the page if no file is selected

0

I have a form where an input of type file is optional, but when submitting the form with id="update" the entire page is reloaded.

$("#update").on('submit',(function(e) {

    var fsize = $('#subir_archivo')[0].files[0].size;
    var ftype = $('#subir_archivo')[0].files[0].type;

    //Validate size
    if(fsize>5000000){
         toastr["error"]("Limite de tamaño excedido", "Archivo inválido")
        return false;
    }

    switch(ftype)
    {
        case 'image/jpeg':
            break;
        case 'image/jpg':
            break;
        case 'image/png':
            break;
        case 'image/gif':
            break;
        default:
            toastr["error"]("Solo se admiten ", "Archivo inválido")
            return false;
    }

    e.preventDefault();
    $.ajax({
        url: "assets/contentHtml/uploadLog.php",
        type: "POST",
        data:  new FormData(this),
        contentType: false,
        cache: false,
        processData: false,
        dataType: 'json',
        success: function(data){
            console.log(data);
            if (data.status == false) {
                toastr.error(data.msn);
            }else{
                toastr.success(data.msn);
            }
        },
        error: function(data){
            console.error(data);
        }
    });
}));

If I select a file to upload, the process is carried out normally, but when I omit the file, it simply reloads the page, which I'm missing?

    
asked by Fernando Garcia 28.11.2018 в 03:56
source

1 answer

0

Notice if the console throws you some error , finally, add a return false in your ajax request at the end and in the HTML remove the input type "submit" and put it type "button" that will make the form never do a submit unless you send it with an ajax

    
answered by 28.11.2018 в 04:17