Validating input file with ajax request

Asked

Viewed 674 times

2

Whenever I give a Submit in the form appears an error in the line in which this variable $file, I disabled the ajax and did not appear the error, so I guess it is not php problem

$(document).ready(function() {
  $('.formulario').submit(function() {
    $.ajax({
      url: 'enviar.php',
      type: 'POST',
      data: $('.formulario').serialize(),
      success: function(valor) {
        $('.resp').html(valor);
      },
      beforeSend: function() {
        $('.resp').html('<div class="resposta email-aguarde email-nao-validado"><span>Aguarde enquanto enviamos seus dados</span><span><img src="ajax-loader.gif" alt=""/></span></div>');
      }
    });
    return false;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="resp"></div>
  <form class="formulario" method="post">
    <input class="nome" type="text" name="nome" placeholder="Nome" />
    <input class="email" type="text" name="email" placeholder="E-Mail" />
    <input class="telefone" type="text" name="telefone" placeholder="Telefone" />
    <select class="assunto" name="assunto">
      <option>Assunto</option>
      <option value="Dúvidas">Dúvidas</option>
      <option value="Críticas">Críticas</option>
      <option value="Elogios">Elogios</option>
      <option value="Outros">Outros</option>
    </select>
    <textarea class="mensagem" name="mensagem" placeholder="Digite sua mensagem"></textarea>
    <input class="arquivo" type="file" name="arquivo" />
    <input class="enviar" type="submit" value="Enviar Dados" />
  </form>
  <div class="clear"></div>
</div>

send php.

$nome = strip_tags(trim($_POST['nome']));
$email = strip_tags(trim($_POST['email']));
$telefone = strip_tags(trim($_POST['telefone']));
$assunto = strip_tags(trim($_POST['assunto']));
$mensagem = strip_tags(trim($_POST['mensagem']));
$arquivo = $_POST['arquivo'];

$tamanho = 5242880; //5 megabytes
$tipos = array(
'image/jpeg',
'image/pjpeg'
); //tipos de arquivos


$erro = array();
if (empty($nome)) {
$erro[] = "Digite seu nome";
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$erro[] = "Digite um e-mail válido";
}
if (empty($telefone)) {
$erro[] = "Digite seu telefone";
}
if (empty($assunto) || $assunto == 'Assunto') {
$erro[] = "Selecione um assunto";
}
if (empty($mensagem)) {
$erro[] = "Digite uma mensagem";
}

if (!is_uploaded_file($arquivo['tmp_name'])) {
$erro[] = 'O arquivo é obrigátorio';
} if ($arquivo['size'] > $tamanho) {
$erro[] = 'O limite do arquivo é de 5 megabytes';
} if (!in_array($arquivo['type'], $tipos)) {
$erro[] = 'O tipo do arquivo permitido é apenas JPEG';
} else if (count($erro) < 1) :

require_once 'phpmailer/PHPMailerAutoload.php';

$Email = new PHPMailer();
$Email->setLanguage('br');

//Define dados do servidor e tipo de conexão
$host = 'smtp.gmail.com';
$username = '';
$senha = '';
$porta = 587;
$secure = 'tsl';

//Email e nome de quem vai receber o email
$receber_email = '[email protected]';
$receber_nome = 'Sérgio Machado';

$from = $username;
$fromName = 'Sérgio Machado';

$Email->isSMTP();
$Email->Host = $host;
$Email->SMTPAuth = true;
$Email->Username = $username;
$Email->Password = $senha;
$Email->Port = $porta;
$Email->SMTPSecure = $secure;

$Email->From = $from;
$Email->FromName = $fromName;
$Email->addReplyTo($email, $nome);
$Email->addAddress($receber_email, $receber_nome);

$Email->isHTML(true);
$Email->CharSet = 'utf-8';
$Email->WordWrap = 70;

$Email->Subject = $assunto;

$body = "<strong>Nome: </strong>{$nome} <br />
    <strong>E-Mail: </strong>{$email} <br />
    <strong>Telefone: </strong>{$telefone} <br />
    <strong>Assunto: </strong>{$assunto} <br />
    <strong>Mensagem: </strong>{$mensagem} <br />
    <strong>Arquivo em anexo: </strong>{$arquivo['name']} <br />";

$Email->msgHTML($body);
$Email->AddAttachment($arquivo['tmp_name'], $arquivo['name']);

//Verifica se a mensagem foi enviada ou não.
if ($Email->Send()) {
    echo '<p class="resposta email-enviado">E-mail enviado com sucesso</p>';
} else {
    echo '<p class="resposta email-nao-enviado">Error: e-mail não enviado,      por favor tente outra vez!</p>';
}
endif;

if (count($erro) >= 1) {
echo '<ul class="resposta email-nao-validado">';
foreach ($erro as $err) {
    echo '<li>' . $err . '</li>';
}
echo '</ul>';
}
  • Sergio think the problem is that file is a key of $_FILES and not $_POST. Change $arquivo = $_POST['arquivo']; for $arquivo = $_FILES['arquivo']; and see what happens. And <form... add enctype="multipart/form-data"

  • And in this line as I told you in the previous answer, it should not be else if (count($erro) < 1) : but yes if (count($erro) < 1) :. This is not the reason for this problem, but correct

  • @Miguel I had already tried with $_FILES but now I added this attributes in the form and keeps giving the same error, in the same line

  • Ha wait there... But with ajax the sending of the files is a little different. Anyway your form must be <form class="formulario" enctype="multipart/form-data" method="post">, server side (php), $_FILES['arquivo']; thus

  • Ready edited and deleted css

  • I’m here for some tests to see if I can help you. Wait a few minutes

Show 1 more comment

2 answers

2


@If Sergio has not changed anything in the code however, do this, step by step, should not fail anything:

When files are mixed we should use Formdata() to send data + files to server when we upload with ajax

HTML changes:

<form class="formulario" enctype="multipart/form-data" method="post">

JS changes (can copy directly):

$(document).ready(function() {
  $('.formulario').submit(function() {
    var form_data = new FormData();
    form_data.append('arquivo', $('input.arquivo').prop('files')[0]);
    form_data.append('nome', $('input.nome').val());
    form_data.append('email', $('input.email').val());
    form_data.append('telefone', $('input.telefone').val());
    form_data.append('assunto', $('select.assunto').val());
    form_data.append('mensagem', $('textarea.mensagem').val());
    console.log(form_data);
    $.ajax({
      url: 'enviar.php',
      type: 'POST',
      data: form_data,
      cache: false,
      contentType: false,
      processData: false,
      success: function(valor) {
        $('.resp').html(valor);
      },
      beforeSend: function() {
        $('.resp').html('<div class="resposta email-aguarde email-nao-validado"><span>Aguarde enquanto enviamos seus dados</span><span><img src="ajax-loader.gif" alt=""/></span></div>');
      }
    });
    return false;
  });
});

PHP changes (send.php) (can copy directly):

$nome = strip_tags(trim($_POST['nome']));
$email = strip_tags(trim($_POST['email']));
$telefone = strip_tags(trim($_POST['telefone']));
$assunto = strip_tags(trim($_POST['assunto']));
$mensagem = strip_tags(trim($_POST['mensagem']));

$tamanho = 5242880; //5 megabytes
$tipos = array(
    'image/jpeg',
    'image/pjpeg'
);


$erro = array();
if (empty($nome)) {
    $erro[] = "Digite seu nome";
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $erro[] = "Digite um e-mail válido";
}
if (empty($telefone)) {
    $erro[] = "Digite seu telefone";
}
if (empty($assunto) || $assunto == 'Assunto') {
    $erro[] = "Selecione um assunto";
}
if (empty($mensagem)) {
    $erro[] = "Digite uma mensagem";
}

if(!isset($_FILES['arquivo'])) {
    $erro[] = 'O arquivo é obrigátorio';
}
else {
    $arquivo = $_FILES['arquivo'];
    if ($arquivo['size'] > $tamanho) {
        $erro[] = 'O limite do arquivo é de 5 megabytes';
    }
    if (!in_array($arquivo['type'], $tipos)) {
        $erro[] = 'O tipo do arquivo permitido é apenas JPEG';
    }
}

if (count($erro) < 1) {
    // enviar email aqui
}
else {
    echo '<ul class="resposta email-nao-validado">';
    foreach ($erro as $err) {
        echo '<li>' . $err . '</li>';
    }
    echo '</ul>';
}

I didn’t copy the sending of the email so it wouldn’t be too long here. I hope it works

  • The error is gone, but the attachment is not coming in the email

  • Ha I thought it was just upload to directory... At this time it should be with extra files in your folder. Sorry. I will edit

  • Edited on top @Sérgiomachado. Try it like this, I changed the server side (php)

  • Perfect! worked exactly as I wanted, just added m little more code in ajax, but it was great, thank you very much

  • It took @Sergio. You’re welcome, however there must be a few images in the directory because the first time I did it was to upload

  • you can make the fields clear after the form is sent?

  • how was this code for the optional image field?

  • It was like @Sérgiomachado. It just changed to if(isset$_FILES['arquivo']()){...// fazer as operações com ficheiro aqui...}, and there is no error if they did not upload, IE, there would be no else { $erro[] = 'O arquivo é obrigátorio'; }afterward.

Show 3 more comments

0

The problem is that AJAX does not support sending files with serialize, and it is necessary to specify content type and process data for false.

try the following:

$('.formulario').submit(function() {
  var formData = new FormData($(this));
  $.ajax({
     url: 'enviar.php',
     type: 'POST',
     cache: false,
     contentType: false,
     processData: false,
    data: formData,
    success: function(valor) {
      $('.resp').html(valor);
    },
    beforeSend: function() {
      $('.resp').html('<div class="resposta email-aguarde email-nao-validado"><span>Aguarde enquanto enviamos seus dados</span><span><img src="ajax-loader.gif" alt=""/></span></div>');
    }
  });
return false;
});
  • It didn’t work, there were more mistakes yet

  • What kind of error ? The file you are picking up with $_FILES?

  • I use the same function, and in php caught the file with $arquivo_tmp = $_FILES['file-0']['tmp_name'];

  • as if the variables did not exist, yes with $_FILES

  • gives a print_r($_FILES) and print_r($_POST) to see what is coming

  • the two functions returns an empty array Array()

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.