return of various error via ajax

Asked

Viewed 167 times

0

I have a little problem regarding the return of errors via ajax, follow the condigo:

Index.php

        <h4>Cadastro de Nome</h4>
                <form id="cadUsuario" method="post">
                    <label>Nome:</label><input required type="text" name="nome" id="nome" />
                    <br/><br/>
                    <input type="submit" value="Salvar" id="salvar" />
                </form>
<script type="text/javascript">
$(function () {    
$("#cadUsuario").submit(function (e) {
e.preventDefault();
var form_data = $(this).serialize(); 
$.ajax({
  type: "POST", 
  url: "salvar.php",
  dataType: "json", // Add datatype
  data: form_data
}).done(function (data) {
 var mensagem = '';

 if (!data.insert){
    mensagem = 'Falha no cadastro';
 }

 if(!data.email){
    mensagem += 'Falha no envio do email';
 }

 if(data.insert && data.email){
    mensagem = 'Operação realizda com sucesso';
 }

 alert(mensagem);
}, "json");
}); 
});

Save.php

    <?php
include "config.php";
if((isset($_POST['nome'])&&$_POST['nome']!="")){ 
$nome = $_POST['nome'];
$sql = "INSERT INTO `nomes` (`idnomes`,`nomes`) VALUES (NULL,'$nome')";

require('mail_config.php');

$resultado = array('insert' => false, 'email' => false); 

$resultado['insert'] = mysql_query($sql);
$resultado['email'] = sendMail("Testando o Mailer","Mensagem de teste do Mailer com Ajax".$nome."","[email protected]","Jefferson Androcles");

echo json_encode($resultado);
}

mail_config.php

<?php function sendMail($assunto,$msg,$destino,$nomeDestino) {
require_once('Mailer/class.phpmailer.php');
$mail             = new PHPMailer();
$mail->IsSMTP(); 
$mail->SMTPAuth   = true;                 
$mail->Host       = 'host';     
$mail->Port       = '587';                   
$mail->Username   = '[email protected]'; 
$mail->Password   = 'Senha';         
$mail->From = '[email protected]';
$mail->FromName = 'AndroclesMail';
$mail->IsHTML(true);
$mail->Subject    = utf8_decode($assunto);
$mail->Body    = utf8_decode($msg);
$mail->AddAddress($destino,utf8_decode($nomeDestino) );
if(!$mail->Send()){
echo '<span>Erro ao enviar, favor entre em contato pelo e-mail [email protected]!</span>';
}else{
}
}
?>

Until then everything is working, except error 2 (there is => 2), I make the error purposely but does not return me anything, the other two, IE, 1 and 3 works normal, can help me? and wanted to know if there are any errors in jquery whether it is a gambiarra or not kkkk, Thank you!

  • 1

    O if $MailEnv === false shouldn’t it be separated? the other two if compare different things ... think about the scenario that Sert failed and the email was successfully sent.

  • So, I’m thinking that now! I’ll test your answer below!

1 answer

2


if is comparing different things (whether done or not and sending email) and uses only a 'bucket' (return array) to play the result.

if($query === false){
    echo json_encode(array('existe' => 1));
} elseif ($MailEnv === false) {
    echo json_encode(array('existe' => 2));
}elseif ($query === true){
    echo json_encode(array('existe' => 3));
}

My suggestion to resolve this is to create an array that has the result of the two operations and then passed to javascript via json_encode(). I started from the point that sendMail() returns a Boolean.

require('mail_config.php');

$resultado = array('insert' => false, 'email' => false); 

$resultado['insert'] = mysql_query($sql);
$resultado['email'] = sendMail("Testando o Mailer","Mensagem de teste do Mailer com Ajax".$nome."","[email protected]","Jefferson Androcles");

echo json_encode($resultado);

The responsibility to check whether everything is right or not is now done by javascript.

.done(function (data) {
    var mensagem = '';

     if (!data.insert){
        mensagem = 'Falha no cadastro';
     }

     if(!data.email){
        mensagem += 'Falha no envio do email';
     }

     if(data.insert && data.email){
        mensagem = 'Operação realizda com sucesso';
     }

     alert(mensagem);
}   
  • It says that failed to send the email, but the email is sent!

  • @Jeffersonandrocles of the one console.log() in data see the values you can put here in the comments.

  • I don’t know if it helps, but that’s the link, http://htcompanyonline.com.br/Teste/

  • don’t work much with jquery, but it would be like this, . done(Function (data) { console.log() Alert(data); }, "json"); why if it is, it appears Object Object

  • @Jeffersonandrocles like this: console.log(data) then in the browser console (usually activated by F12) the values will appear.

  • Object {Insert: true, email: null}, I think the error ta in mail_config.php, I will edit my question and post it!

  • @Jeffersonandrocles this, also check if the SendMail() returns something.

  • I think the problem is after Voce sends the email, because it is not returning anything to the email property of the json that Voce sends to the screen again.

  • In this excerpt you expect a return of the "Sendmail" method, to assign the result to the "email" property: $result['email'] = sendmail("Testing Mailer","Mailer test message with Ajax".$name."","androclesleitegmail.com","Jefferson Androcles"); </span>'; }Else{ } ?

  • it is then, it was that same! PERFECT, thank you very much!

Show 5 more comments

Browser other questions tagged

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