Ajax Jquery return variable giving error

Asked

Viewed 613 times

3

I have the following script on ajax:

  $("#contato").on("submit", function () {
    if($('#descricao').val() == "")   {     //verifica apena o texto
        alert("Descrição não está preenchida!");
        $('#descricao').siblings().each(function(){
          if ($(this).children('iframe').length){
             var iframe=$(this).children('iframe')[0];
             iframe.contentWindow.focus();
          }
       });
       return false;
    } 

    $.ajax({
     url: "_required/email.php",
     type: "POST",
     data: $("#contato").serialize(),
     success: function(retorno){

        if (retorno.trim() == "OK") {
          resposta = "E-mail enviado com sucesso!";
        } else {
          resposta = "Erro no envio do E-mail";
        }
       $(".resposta").css("display", "block");
       $(".resposta").html(resposta);             
     }
    });

    return false;

  }); 

return in Success:, brings back a query to a script php that returns two values, either OK or ERROR.

In that part

   $(".resposta").html(resposta);             

If I change to

   $(".resposta").html(retorno);              

Call me back

OK

But keeping

   $(".resposta").html(resposta);             

Prints

"Erro no envio do E-mail";

Where am I going wrong?

Files involved:

email php.

<?php 
 ini_set("display_errors",true);
 ini_set("display_startup_erros",1);
 error_reporting(E_ALL && E_NOTICE);
 error_reporting( E_ALL | E_STRICT ); // PHP 5.3
 error_reporting( E_ALL ); // Todas as outras versões 
?>

<?php
    require_once "../_controlls/_conexao/Conexao.php";
    require_once "../_controlls/_util/PhpUtil.php";     
    require_once "../_controlls/_models/Emails.php";
    require_once "../_controlls/_daos/EmailsDao.php";
    require_once "../_controlls/_util/Constantes.php";

    $connection = new Conexao(); 
    $conexao = $connection->abreConexao();
    $constantes = new Constantes();  
    $phpUtil = new PhpUtil();

    $assunto = $phpUtil->contatoTipos($_POST["assunto"]);   
    $emailsDao = new EmailsDao($conexao);

    $email = new Emails(
                     date("Y-m-d"), 
                     "n", 
                     $_POST["nome"], 
                     $_POST["email"], 
                     preg_replace( '#[^0-9]#', '', $_POST["telefone"] ),
                     $_POST["assunto"], 
                     $_POST["descricao"]);

    $emailsDao->cadastrar($email);

    $outro = $_POST["assunto"] == 6 ? "<b>Qual:</b> ".$_POST["qual"]."<br /><br />" : "";   

    $texto  = "<h2>".$constantes->getTituloSite()."</h2><br />";
    $texto .= "<img style='display:block; margin:0 auto;' src='".$constantes->getHttpSite()."/_img/logo.png' />";
    $texto .= "<b>Olá, você nos enviou um e-mail com a seguinte mensagem:</b><br /><br />";
    $texto .= "<b>Nome:</b> ".$_POST["nome"]."<br /><br />";
    $texto .= "<b>Telefone:</b> ".$_POST["telefone"]."<br /><br />";
    $texto .= "<b>E-mail:</b> ".$_POST["email"]."<br /><br />";
    $texto .= "<b>Interesse:</b> ".$assunto."<br /><br />";
    $texto .= $outro;
    $texto .= "<b>Descrição:</b><br />".nl2br($_POST["descricao"])."<br /><br /><br />";
    $texto .= "Estaremos respondendo o mais rápido possível<br /><br />";

    require_once "../_controlls/_models/EmailEnviar.php";
    require_once "../_controlls/_daos/EmailEnviarDao.php";

    $html = "<!doctype html>
             <html>
              <head>
                <meta charset='utf-8'>
                <title>".$constantes->getTituloSite()."/title>
              </head>           
              <body>".$texto."</body>
             </html>";

    $assuntoCodificado = sprintf('=?%s?%s?%s?=', 'UTF-8', 'Q', quoted_printable_encode("Re: ".$assunto));


    $emailEnviar = new EmailEnviar( 
          $_POST["nome"], 
          $_POST["email"],
          $constantes->getTituloSite(), 
          "[email protected]",
          $assuntoCodificado,
          $texto
    );

    $emailEnviarDao = new EmailEnviarDao();

    $enviarEmail = $emailEnviarDao->enviaEmail($emailEnviar);   

    if ($enviarEmail["success"] == 1) {

        echo "OK";

    } else {

        echo "ERRO";

    }

?>

Email.php // Here a class

<?php

  class Emails {

      private $idEmail;
      private $data;
      private $respondidoData;
      private $respondido;
      private $nome;
      private $email;
      private $telefone;
      private $assunto;
      private $descricao;

      public function __construct (
          $_data,
          $_respondido,
          $_nome, 
          $_email, 
          $_telefone, 
          $_assunto, 
          $_descricao) {

          $this->data = $_data;
          $this->respondido = $_respondido;
          $this->nome = $_nome;
          $this->email = $_email;
          $this->telefone = $_telefone;
          $this->assunto = $_assunto;
          $this->descricao = $_descricao;
      }


      public function setIdEmail ($_idEmail) {
          $this->idEmail = $_idEmail;
      }

      public function setRespondidoData ($_respondidoData) {
          $this->respondidoData = $_respondidoData;
      }           

      public function getIdEmail () {
          return $this->idEmail;
      }

      public function getData () {
          return $this->data;
      }

      public function getRespondidoData () {
          return $this->respondidoData;
      }

      public function getRespondido () {
          return $this->respondido;
      }

      public function getNome () {
          return $this->nome;
      }

      public function getEmail () {
          return $this->email;
      }

      public function getTelefone () {
          return $this->telefone;
      }

      public function getAssunto () {
          return $this->assunto;
      }

      public function getDescricao() {
          return $this->descricao;
      }
  }

?>

Emaildao.php //Here Method class

<?php 

 class EmailsDao {

     private $conexao;

     public function __construct ($_conexao) {      
         $this->conexao = $_conexao;
     }

     public function responder ($idEmail) {

         $string = "UPDATE emails 
                    SET respondido = 's' , respondidoData = NOW() 
                    WHERE idEmail = ".$idEmail;

        $this->conexao->query($string);
     }

     public function excluir ($idEmail) {        

         $string = "DELETE FROM emails WHERE idEmail = ".$idEmail;

         $this->conexao->query($string);

     }

     public function cadastrar ($email) {        

         $string = "INSERT INTO emails (data, respondido, nome, email, telefone, assunto, descricao) VALUES ('".$email->getData()."','".$email->getRespondido()."','".$email->getNome()."','".$email->getEmail()."','".$email->getTelefone()."','".$email->getAssunto()."','".$email->getDescricao()."')";

         $this->conexao->query($string);

     }

     public function pesquisaEmail($idEmail) {
         $email = null;           

         $string = "SELECT 
                       idEmail, 
                       data, 
                       respondidoData, 
                       respondido, 
                       nome, 
                       email, 
                       telefone, 
                       assunto, 
                       descricao
                    FROM emails 
                    WHERE idEmail = ".$idEmail;

         $registros = $this->conexao->query($string);
         $quantasLinhas = $registros->num_rows;      

         if ($quantasLinhas > 0) {

             list ($idEmail, $data, $respondidoData, $respondido, $nome, $email, $telefone, $assunto, $descricao) = $registros->fetch_row();

             $email = new Emails($data, $respondido, $nome, $email, $telefone, $assunto, $descricao);                        
             $email->setIdEmail($idEmail);
             $email->setRespondidoData($respondidoData);
         }

         return $email;

     }

     public function pesquisaEmails() {
         $emails = null;           

         $string = "SELECT idEmail, data, respondidoData, respondido, nome, email, telefone, assunto, descricao FROM emails";

         $registros = $this->conexao->query($string);
         $quantasLinhas = $registros->num_rows;      

         if ($quantasLinhas > 0) {

             while (list ($idEmail, $data, $respondidoData, $respondido, $nome, $email, $telefone, $assunto, $descricao) = $registros->fetch_row()) {

             $email = new Emails($data, $respondido, $nome, $email, $telefone, $assunto, $descricao);                        
             $email->setIdEmail($idEmail);
             $email->setRespondidoData($respondidoData);

             $emails[] = $email;
             }
         }

         return $emails;

     }

 }
?>

Emailsenviar.php

<?php

 class EmailEnviar {

   private $nomeAlvo;
   private $emailAlvo;
   private $nomeRemete;
   private $emailRemete;
   private $assunto;
   private $mensagem;

   public function __construct(
      $_nomeAlvo, 
      $_emailAlvo, 
      $_nomeRemete, 
      $_emailRemete, 
      $_assunto,
      $_mensagem

      )  {

        $this->nomeAlvo = $_nomeAlvo;
        $this->emailAlvo = $_emailAlvo;
        $this->nomeRemete = $_nomeRemete;
        $this->emailRemete = $_emailRemete;
        $this->assunto = $_assunto;
        $this->mensagem = $_mensagem;
   }

   public function getNomeAlvo () {
       return $this->nomeAlvo;
   }

   public function getEmailAlvo () {
       return $this->emailAlvo;
   }

   public function getNomeRemete () {
       return $this->nomeRemete;
   }

   public function getEmailRemete () {
       return $this->emailRemete;
   }

   public function getAssunto () {
       return $this->assunto;
   }

   public function getMensagem () {
       return $this->mensagem;
   }

}

Emailenviardao.php

<?php

  class EmailEnviarDao {

    public function __construct() {}

    public function enviaEmail($email)  {

      $cabecalhos  = 'MIME-Version: 1.0' . "\r\n";
      $cabecalhos .= 'Content-type: text/html; charset=utf-8' . "\r\n";
      $cabecalhos .= 'To: '.$email->getNomeAlvo().' <'.$email->getEmailAlvo().'>' . "\r\n";
      $cabecalhos .= 'From: '.$email->getNomeRemete().' <'.$email->getEmailRemete().'>' . "\r\n";


      if(mail($email->getEmailAlvo(), $email->getAssunto(), $email->getMensagem(), $cabecalhos)) {

         return array('success'=>'1','errors'=>'0K');

      } else {

          return array('success'=>'0','errors'=>"Não conseguimos enviar o e-mail");

      }    

    }   

  }

?>  
  • 1

    What gives console.log(retorno.length);?

  • it is, 6; but php only returns 2 which is OK. There is something else coming. Please have a look: http://www.hotplateprensas.com.br/contact.php. can add any email to this page

  • Forehead if (retorno.trim() == "OK"){... works?

  • 1

    It worked. Where are these hidden characters coming from? Is it from a file with GOOD signature?

2 answers

4


I took a look at your website and the return of AJAX.

I saw this:

inserir a descrição da imagem aqui

At first it seems correct, the OK is there... but the problem is that it has blank space and line break before of OK, making it a string with more characters than only OK.

Looking at a breakpoint in Javascript confirms:

inserir a descrição da imagem aqui

You have to fix that in PHP. And that code is not in the question. Somewhere you’re doing echo empty or with whitespace.

To "hide" the problem in Javascript you can do

success: function(retorno){    
    if (retorno.trim() == "OK") {

or

success: function(retorno){    
    retorno = retorno.split(/\W/).join('');
    if (retorno == "OK") {
  • 1

    I’ll take it easy, thanks!

  • Please, I’ve added to the question all the files involved. I couldn’t find where these spaces are being generated and none of these files have BOM signature. And I also put all the Java Script

  • @Carlosrocha tests to remove the error tools that are at the beginning of the file, ini_set etc....

  • 1

    Look, it worked. But you can’t understand why these directives are inserting these characters!

0

In ajax there are some functions, one of them Success and the other error.

  $.ajax({
                url: url
                success: function (parametro) { ... }, 
error: function(){....}

use the error of the function that will help your life.

Browser other questions tagged

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