Question:
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) {
event.preventDefault();
var formulario = $('#formalta');
var datos = formulario.serialize();
var archivos = new FormData();
var url = 'funciones/alta.php';
$.ajax({
url: url + '?' + datos,
type: 'POST',
contentType: false,
data: archivos,
processData: false,
success: function (data) { Hace algo cuando funciona. },
error: function (xhr, ajaxOptions,thrownError) {
alert(thrownError);}
});//ajax-PDF
});//submit
PHP code
$m=$db->lastInsertId();
if($_FILES['pdfFile']['name']!= ''){
if ($_FILES['pdfFile']['type']!="application/pdf."){
$extension = strrchr($_FILES['pdfFile']['name'],'.' );
$_FILES['pdfFile']['name']=$m.''.$extension;
$serverPath='../../TTS/pages/calibration/files';
$tempPath=$_FILES['pdfFile']['tmp_name'];
$fileName= $_FILES['pdfFile']['name'];
$format = $_FILES['pdfFile']['type'];
$destiny=$serverPath.'/'.$fileName;
$bdPath='files'.'/'.$fileName;
$queryUpdate="UPDATE calibrationtbltemp SET pdf='$bdPath' where id=$m";
$queryUpdateEx=$db->runQuery($queryUpdate) or die("no se ejecuto");
if($queryUpdateEx){
$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
Answer:
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
}