Problem with an upload file and Ajax

0

Dear community, I told you that I made an sript to upload files to the server. Use html5, jquery / ajax and php. Up there all right, the issue is that now I want to get an alert type confirm in the case that the name of the file already exists on the server. The problem I have with the implementation of Ajax.

Here I leave my code, I think I have a logic error, since I am a lammer haha. Then I leave the ajax script:

$(function(){
    $("#formuploadajax").on("submit", function(e){
        e.preventDefault();
        var f = $(this);
        var formData = new FormData(document.getElementById("formuploadajax"));
        formData.append("dato", "valor");
       $('#target').hide();
        $('#mensaje').html('<center><strong>¡Atención!</strong> El archivo se está subiendo. Esto puede demorar unos segundos...</center>');
        //aca verifico si existe (en teoria :-p)
        $.ajax({
            url: "php/verificarArchivo.php",
            type: "post",
            dataType: "html", 
            data: formData,
            cache: false,
            contentType: false,
            processData: false

            success:function(r){
  if(r==1){

    //si existe pregunta si desea reemplazar
alertify.confirm('El archivo existe, ¿Desea reemplazar?', 
      function(){
        $.ajax({
            url: "php/uploadimage.php", //php para subir archivo
            type: "post",
            dataType: "html", 
            data: formData,
            cache: false,
            contentType: false,
            processData: false
                          success:function(r){
if(r==1){

    alertify.success("Actualizado con exito :)");
  }else{
    alertify.error("Fallo el servidor :(");
  }
   }


});

      }, function(){ alertify.error('Se cancelo')};


        //si no existe lo subo con uploadimage.php
          } else {
             $.ajax({
            url: "php/uploadimage.php",
            type: "post",
            dataType: "html", 
            data: formData,
            cache: false,
            contentType: false,
            processData: false
            success:function(r){
                if(r==1){

               alertify.success("Actualizado con exito :)");
                  }else{
               alertify.error("Fallo el servidor :(");
             }
              }
              });

            }

                });

            });
           });

Sorry if your eyes hurt. The console does not throw me any errors but does not do any of the functions.

I also leave the script that works, but this one just uploads the file:

    $(function(){
    $("#formuploadajax").on("submit", function(e){
        e.preventDefault();
        var f = $(this);
        var formData = new 
       FormData(document.getElementById("formuploadajax"));
        formData.append("dato", "valor");
       $('#target').hide();
        $('#mensaje').html('<center><strong>¡Atención!</strong> El archivo 
         se está subiendo. Esto puede demorar unos segundos...</center>');
        //formData.append(f.attr("name"), $(this)[0].files[0]);
        $.ajax({
            url: "php/uploadimage.php",
            type: "post",
            dataType: "html", 
            data: formData,
            cache: false,
            contentType: false,
   processData: false
        })
            .done(function(res){
                $("#mensaje").html("Listo!"); 
                window.location.reload();

            });
    });
});

The idea would be that based on this code expand to check if there is previously the name in the bd. If so, ask if you want to replace. And in the case that it does not exist, upload it without consulting.

    
asked by Santiago Gonzalez 29.11.2017 в 14:09
source

1 answer

1

Try this way, separating the requests into functions:

  • get only the name of the file, and make the request to see if it exists or not:
  • function uploadFileControler() {
      // OBTIENE EL ARCHIVO
      var file = document.getElementById("formuploadajax");
      // OBTIENE SOLO EL NOMBRE DEL ARCHIVO
      var fileName = file.files[0].name;
    
      $('#target').hide();
      $('#mensaje').html(
        '<center><strong>¡Atención!</strong>' +
        'El archivo se está subiendo. ' +
        'Esto puede demorar unos segundos...</center>'
      );
    
      //guarda la respuesta de si existe o no el archivo
      var existFile = checkFile(fileName);
    };
    
    //hace una petición al servidor para verificar 
    //si existe o no ya el archivo
    function checkFile(name) {
      var exist = false; //guarda un booleano si existe o no
    
      //petición para verificar existencia
      $.ajax({
        url: "php/verificarArchivo.php",
        type: "post",
        async: false, //esto hace que el script espere la respuesta del servidor antes de continuar
        data: fileName, //envia unicamente el nombre, lo verifica en php y retorna la respuesta
        success: function(response) {
          //si existe
          if (response === 1) {
            exist = true;
          }
        }
      });
    
      return exist;
    };
  • Define a function so that you do not repeat the request to load the file and call it whenever you want:
  • //petición para cargar el archivo
    function uploadFile(file){
      //formatData para el archivo antes de enviarlo
      var data = new FormData(file);
    
      //petición
      $.ajax({
        url: "php/uploadimage.php", //php para subir archivo
        type: "post",
        async: false,
        dataType: "html",
        data: data,
        cache: false,
        contentType: false,
        processData: false
        success: function(r) {
          if (r == 1) {
            alertify.success("Actualizado con exito :)");
          } else {
            alertify.error("Fallo el servidor :(");
          }
        }
      });
    };
  • Now a function that with the answer of if it exists or not, define how to upload the file, if with verification or upload it once
  • //decide si pedir verificación para reemplazar archivo o subirlo de una vez
    function responseFile(exist){
      //define que hacer si existe o no existe
      //si existe el archivo
      if (exist) {
        alertify.confirm(
          'El archivo existe, ¿Desea reemplazar?',
          uploadFile(file),
          alertify.error('Se cancelo')
        );
      }else{
        uploadFile(file);
      }
    }
  • Finally it is necessary to call the previous function, passing as a parameter the answer of the server of whether the file exists or not:
  •   //guarda la respuesta de si existe o no el archivo
      /*var existFile = checkFile(fileName);*/
      responseFile(existFile);

    complete would be like this:

    //llama a esta funcion con un onclick en el boton de subir archivo en HTML
    //esta funcion es el controlador para subir el archivo
    function uploadFileControler() {
      // OBTIENE EL ARCHIVO
      var file = document.getElementById("formuploadajax");
      // OBTIENE SOLO EL NOMBRE DEL ARCHIVO
      var fileName = file.files[0].name;
    
      $('#target').hide();
      $('#mensaje').html(
        '<center><strong>¡Atención!</strong>' +
        'El archivo se está subiendo. ' +
        'Esto puede demorar unos segundos...</center>'
      );
    
      //guarda la respuesta de si existe o no el archivo
      var existFile = checkFile(fileName);
      responseFile(existFile);
    };
    
    //hace una petición al servidor para verificar 
    //si existe o no ya el archivo
    function checkFile(name){
        var exist = false; //guarda un booleano si existo o no
    
        //petición para verificar existencia
        $.ajax({
          url: "php/verificarArchivo.php",
          type: "post",
          async: false, //esto hace que el script espere la respuesta del servidor antes de continuar
          data: fileName, //envia unicamente el nombre, lo verifica en php y retorna la respuesta
          success: function(response) {
            //si existe
            if (response === 1) {
              exist = true;
            }
          }
        });
    
        return exist;
    };
    
    //decide si pedir verificación para reemplazar archivo o subirlo de una vez
    function responseFile(exist){
      //define que hacer si existe o no existe
      //si existe el archivo
      if (exist) {
        alertify.confirm(
          'El archivo existe, ¿Desea reemplazar?',
          uploadFile(file),
          alertify.error('Se cancelo')
        );
      }else{
        uploadFile(file);
      }
    }
    
    //petición para cargar el archivo
    function uploadFile(file){
      //formatData para el archivo antes de enviarlo
      var data = new FormData(file);
    
      //petición
      $.ajax({
        url: "php/uploadimage.php", //php para subir archivo
        type: "post",
        async:false,
        dataType: "html",
        data: data,
        cache: false,
        contentType: false,
        processData: false
        success: function(r) {
          if (r == 1) {
            alertify.success("Actualizado con exito :)");
          } else {
            alertify.error("Fallo el servidor :(");
          }
        }
      });
    };

    I hope it's clear, good luck!

        
    answered by 29.11.2017 в 16:28