File upload to ftp through Ajax

0

Good morning. I'm trying to make a form that uploads files to an FTP using PHP. The problem is that the page is reloaded when the upload is executed. I know that in order to just cool an area you have to use AJAX, but I can not execute the upload using it. Below I show the HTML form:

<form id="subida" action="php/upload-ftp.php" method="post" enctype="multipart/form-data">  
  <div>  
  <label for="upload">Selecciona un fichero</label>  
  <input name="upload" type="file" id="file" />  
  <input type="submit" name="submit" value="Enviar" id="btnUpload"/>  
  </div>  
</form>

This HTML directs to the next PHP that executes the upload successfully:

<?php    

$ destination = $ _COOKIE ['route']. "/ uploads /";

if (isset ($ _ POST ['submit'])) {

  if (!empty($_FILES['upload']['name'])) {  
    $ch = curl_init();  
    $localfile = $_FILES['upload']['tmp_name'];  
    $fp = fopen($localfile, "r");  
    curl_setopt($ch, CURLOPT_URL, "URL_de_FTP+PUERTO/".$destino.$_FILES['upload']['name']);  
    curl_setopt($ch, CURLOPT_UPLOAD, 1);  
    curl_setopt($ch, CURLOPT_INFILE, $fp);  
    curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));  
    curl_exec ($ch);  
    $error_no = curl_errno($ch);  
    curl_close ($ch);  
    if ($error_no == 0) {  
      $error = "Fichero subido correctamente.";  
    } else {  
      $error = "Error al subir el fichero.";  
    }  
  } else {  
    $error = "Selecciona un fichero.";  
  }  
}  

? >

The question is, how to execute this process through AJAX? I have tried in different ways, but I have never made it work. Thank you very much for the help.

    
asked by AntonioMP87 16.09.2017 в 13:26
source

1 answer

1

function sendForm(event){
    event.preventDefault();
    var formd = new FormData(event.currentTarget);
    $.ajax({
            url: event.currentTarget.getAttribute('action'),
            method: "POST",
            dataType: 'json',
            data: formd,
            processData: false,
            contentType: false,
            success: function(r){
//La respuesta ha ido bien y esta grabada en la variable r
},
            error: function(er){
                alert('Error de Formulario');
            }
    });
}

To the form put:


getElementById().addEventListener('submit',sendForm(),false);
    
answered by 16.09.2017 / 14:38
source