javascript – Sending AJAX files


I am creating a form and in addition to filling in the data I need to give the user the option to send a PDF file. This is optional. The user may well decide not to attach anything.

I do the Ajax submission by serializing the data and using the FormData object for the file. It works perfect except when the file is empty. It throws me an error because it does not recognize the element.

Ajax code

$('#formalta').submit(function (event) {
     var formulario = $('#formalta');
     var datos = formulario.serialize();
     var archivos = new FormData();
     var url = 'funciones/alta.php';

              url: url + '?' + datos,
              type: 'POST',
              contentType: false,
              data: archivos,
              processData: false,
              success: function (data) {  Hace algo cuando funciona. }, 
              error: function (xhr, ajaxOptions,thrownError) {


PHP code

  if($_FILES['pdfFile']['name']!= ''){
    if ($_FILES['pdfFile']['type']!="application/pdf."){
      $extension = strrchr($_FILES['pdfFile']['name'],'.' );
       $fileName= $_FILES['pdfFile']['name'];
       $format = $_FILES['pdfFile']['type'];
       $queryUpdate="UPDATE calibrationtbltemp SET pdf='$bdPath' where id=$m";
       $queryUpdateEx=$db->runQuery($queryUpdate) or die("no se ejecuto");
                   $resultado = copy($_FILES["pdfFile"]["tmp_name"], $destiny);

         }//if queryUpdateEx

         }//if type is not application/pdf
      }  //empty
     echo $m;

The error I get is:

Notice: Undefined index: pdfFile in C: \ wamp \ www \ Calibration \ functions \ alta.php on line 27


If the error is php could do an isset to validate if they sent the file or not:

if (isset($_POST['file']) {
  //procesar solo si existe el archivo
Scroll to Top