The page is restarted after uploading the second file

1

I created a file upload works well when it's the first time I upload a file, when I try again, if you upload the file, what you should not do is reload the page since I use Ajax to send this, I'm new to the subject and I've searched a lot and I can not find a solution.

$(document).ready(function () {

$(".messages").hide();    
var fileExtension = "";  
$(':file').change(function ()
{        
    var file = $("#imagen")[0].files[0];        
    var fileName = file.name;        
    fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);        
    var fileSize = file.size;        
    var fileType = file.type;       
    showMessage("<span class='info'>Archivo para subir: " + fileName + ", peso total: " + fileSize + " bytes.</span>");
});

$(':button').click(function () {        
    var formData = new FormData($(".formulario")[0]);
    var message = "";        
    $.ajax({
        url: 'upload.php',
        type: 'POST', 
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        beforeSend: function () {
            message = $("<span class='before'>Subiendo la imagen, por favor espere...</span>");
            showMessage(message)
        },            
        success: function (data) {
            message = $("<span class='success'>La imagen ha subido correctamente.</span>");
            showMessage(message);
            if (isImage(fileExtension))
            {
                $(".showImage").html("<img class='img-thumbnail img-fluid' style='height: 400px;width: 400px;'src='files/" + data + "' />");
                $(".hiden_name").html("<p>"+ data +"'<p/>");                                          
            }
        },

        error: function () {
            message = $("<span class='error'>Ha ocurrido un error.</span>");
            showMessage(message);
        }
    });
});

})

function showMessage (message) {     $ (". messages"). html (""). show ();     $ (". messages"). html (message); }

function isImage (extension) {     switch (extension.toLowerCase ())     {         case 'jpg':         case 'gif':         case 'png':         case 'jpeg':             return true;             break;         default:             return false;             break;     } }

front-end

  <div class="container">
        <form enctype="multipart/form-data" class="formulario">
            <label>Subir un archivo</label><br />
            <input name="archivo" type="file" id="imagen" ><br /><br />                
        </form>
        <button id="enviarDatos" class="btn btn-success">Enviar datos</button> <br /><br />              
        <!--div para visualizar mensajes-->
        <div class="messages"></div><br /><br />
        <!--div para visualizar en el caso de imagen-->
        <div class="showImage "  ></div>
        <div class="hiden_name">            
        </div>
    </div>

archivo.php

<?php

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') 
{


$file = $_FILES['archivo']['name'];


if(!is_dir("files/")) 
    mkdir("files/", 0777);


if ($file && move_uploaded_file($_FILES['archivo']['tmp_name'],"files/".$file))
{

}
}else{
    throw new Exception("Error Processing Request", 1);   
}
    
asked by Aaron M Fonseca 06.04.2018 в 06:33
source

2 answers

1

The problem is that you have a button inside the form and you take it as a submit, that's why the page is reloaded, as it does not have an action defined in the form.

SOLUTION:

  

Try to get that button out of the form and call it how you come doing it.

<button id="enviarDatos" class="laclasequeledescss">Enviar datos</button>

And call him like this:

$('#enviarDatos').click(function () {

Try it and tell me

    
answered by 06.04.2018 в 09:03
1

If you do not want me to submit, change the return value of the function, in the success event.

$.ajax({
    url: 'upload.php',
    type: 'POST',        
    data: formData,     
    cache: false,
    contentType: false,
    processData: false,

    beforeSend: function () {
        message = $("<span class='before'>Subiendo la imagen, por favor espere...</span>");
        showMessage(message)
    },

    success: function (data) {
        message = $("<span class='success'>La imagen ha subido correctamente.</span>");
        showMessage(message);
        if (isImage(fileExtension))
        {
            $(".showImage").html("<img class='img-thumbnail img-fluid' style='height: 400px;width: 400px;'src='files/" + data + "' />");
            $(".hiden_name").html("<p>"+ data +"'</p>");
             //return true; // El input lo tienes dentro de un form, evita el submit
             return false;
        }
    },      
    error: function () {
        message = $("<span class='error'>Ha ocurrido un error.</span>");
        showMessage(message);
    }
});
    
answered by 06.04.2018 в 11:51