Does not return the AJAX response

1

Good I have a registration form in which they fill in the data and through AJAX I insert the data in the database. Until then it worked perfectly and I returned a response in notification mode with TOAST.

But when putting in the file that also sends it by mail, the notification stops working but it inserts the record. Step to detail the code.

AJAX

$(function(){
 $("#formuploadajax1").on("submit", function(e){
 e.preventDefault();
   if (comprobar_dni($('#nif').val()) == false) {
   toastr["error"]("El DNI/NIF no es correcto!", "Mensaje");
   return;
 }
  var f = $(this);
  var formData = new FormData(document.getElementById("formuploadajax1"));
  formData.append("dato", "valor");
  //formData.append(f.attr("name"), $(this)[0].files[0]);
  $.ajax({
    url: "incluCuenta/insertar-cliente.php",
    type: "post",
    dataType: "html",
    data: formData,
    cache: false,
    contentType: false,
    processData: false
    })
    .done(function(res){
      if(res=="1"){
      toastr["info"]("Registro exitoso!", "Mensaje")
      setTimeout(function () {
      window.location.href = "login.php"; //will redirect to your blog page (an ex: blog.html)
     }, 1500); //will call the function after 2 secs
     }else{
       $("#mensaje").html(res);
       toastr["error"]("Utiliza otro usuario!", "Mensaje")
     }
     });
          });
      });

What makes me now is that it takes me out of (res) it takes out the value that is in "else"

I detail the insert-client.php It's a bit long will have scroll

<?php
include "../conexion/conexion.php";

mysqli_set_charset($mysqli, "utf8");
$results = 'SELECT * FROM Usuarios';
$rec = mysqli_query($mysqli, $results);

if ($rec === false) {
die('ERROR SQL: ' . htmlspecialchars(mysqli_error($mysqli)));
}
while ($results = mysqli_fetch_object($rec)) {

if(mb_strtolower($results->Username) == mb_strtolower($_POST['email'])) 
{

  die('<div class=\'form\'> 
     <div class="alert alert-danger" style="font-size: 14px;"><strong>¡Error!</strong> Este usuario ya esta en uso.</div>         
    </div>');
  }

}

$name = mysqli_real_escape_string($mysqli, $_POST['name']);
$email = mysqli_real_escape_string($mysqli, $_POST['email']);
$telefono = mysqli_real_escape_string($mysqli, $_POST['telefono']);
$movil = mysqli_real_escape_string($mysqli, $_POST['movil']);
$nif = mysqli_real_escape_string($mysqli, $_POST['nif']);
$direccion = mysqli_real_escape_string($mysqli, $_POST['direccion']);
$postal = mysqli_real_escape_string($mysqli, $_POST['postal']);
$poblacion = mysqli_real_escape_string($mysqli, $_POST['poblacion']);
$provincia = mysqli_real_escape_string($mysqli, $_POST['provincia']);
$pass = mysqli_real_escape_string($mysqli, $_POST['pass']);
$sexo = mysqli_real_escape_string($mysqli, $_POST['sexo']);
$fecha = date('y,m,d');

$results = "
INSERT INTO Usuarios (
    Fecha,
    Sexo,
    Nombre,
    Password,
    Username,
    Direccion,
    Postal,
    Poblacion,
    Provincia,
    Telefono,
    Movil,
    Dni,
    intestado
) VALUES (
    '$fecha',
    '$sexo',
    '$name',
    '$pass',
    '$email',
    '$direccion',
    '$postal',
    '$poblacion',
    '$provincia',
    '$telefono',
    '$movil',
    '$nif',
    '1'
  )
";
if (mysqli_query($mysqli, $results) === false) {
die('Error SQL: ' . htmlspecialchars(mysqli_error($mysqli)));
}
echo "1";

include "../plantillaEmail/template.php";
include "../PHPMailer/class.phpmailer.php";
include "../PHPMailer/class.smtp.php";



$email_user = "usuario";
$email_password = "pass";
$the_subject = "Bienvenid@ $name";
$address_to = "$email";
$from_name = "Depildiodo";
$phpmailer = new PHPMailer();
$phpmailer->Username = $email_user;
$phpmailer->Password = $email_password; 
$phpmailer->CharSet = 'UTF-8';
$phpmailer->SMTPSecure = 'ssl';
$phpmailer->Host = "mail.depildiodo.com"; // GMail
$phpmailer->Port = 465;
$phpmailer->IsSMTP(); // use SMTP
$phpmailer->SMTPAuth = true;
$phpmailer->setFrom($phpmailer->Username,$from_name);
$phpmailer->AddAddress($address_to); // recipients email
$phpmailer->Subject = $the_subject; 
$phpmailer->Body = $body;
$phpmailer->IsHTML(true);
$phpmailer->Send();
?>

The problem is to add the include "../plantillaEmail/template.php"; is to put this line that is the one that prints the template of the mail and I no longer get the notification well.

The template.php

<?php $body="aqui esta todo el contenido de la plantilla";?>
    
asked by Miguel 04.10.2018 в 09:00
source

2 answers

0

You've already tried using typeof instead of ==, that is, if you can use, if (typeof res == 'number' & amp & parseInt (res) == 1) it is likely that the answer is not thrown with the proper format, another technique is to use console.log (res); so that you break down the results.

you can also see with

  .done(function(res){
       res = parseInt(res.trim().replace(/\D+/g, ""));
       if(res==1){}
       else{}
   })

It is likely that you are not receiving the HTTP response correctly, it should be 200

    
answered by 04.10.2018 / 09:35
source
0
//Indicas todos los campos que necesites por POST
$need = array(
    "name",
    "email",
    "telefono",
    "movil",
    "nif",
    "direccion",
    "postal",
    "poblacion",
    "provincia",
    "pass",
    "sexo",
    "fecha",
);
$var = array();
foreach ($need as $key) {
    /*En caso de que no tengas el campo por POST*/
    if (!empty($_POST[$key])) {
        switch ($key) {
            case 'name':
                return "Necesitas un nombre";
                break;
            /*
                Continuas las validaciones
            */
            default:
                # code...
                break;
        }
    }
    /*En caso de que el campo sea válido*/
    else{
        $var[$key] = mysqli_real_escape_string($mysqli,$_POST[$key]);
    }
}
$fecha = date('y,m,d');
print_r($var);
    
answered by 04.10.2018 в 09:56