Error returning AJAX data

0

My code is working to the point where ajax has to get the answer to print on the screen, the insert is normally done in bd, if it changes the return $ ("# requests"). for $ ("# requests"). html (data); does it work by returning serialize, is something escaping me?

    <script type="text/javascript">
jQuery(document).ready(function(){
    jQuery('#pedidos').submit(function(){
        var dados = jQuery( this ).serialize();

        jQuery.ajax({
            type: "POST",
            url: "pedidos.php",
            data: dados,
            success: function( data )
            {
                $("#pedidos").html(data); 
            }
        });

        return false;
    });
   });
  </script>

below the php page

   $nome = trim($_POST['nome']);
  $recado = trim($_POST['recado']);
  $error = FALSE;

  if (!$error) {
 $sql = "INSERT INTO 'pedidos' ('nome', 'recado') VALUES "
        . "( :nome, :recado)";

try {
  $stmt = $DB->prepare($sql);

  // bind the values
  $stmt->bindValue(":nome", $nome);
  $stmt->bindValue(":recado", $recado);


  // execute Query
  $stmt->execute();
  $result = $stmt->rowCount();
  if ($result > 0) {
    $_SESSION["errorType"] = "success";
    $_SESSION["errorMsg"] = "Sua mensagem foi enviada com Sucesso.";
  } else {
    $_SESSION["errorType"] = "danger";
    $_SESSION["errorMsg"] = "Falha ao enviar.";
  }
} catch (Exception $ex) {

  $_SESSION["errorType"] = "danger";
  $_SESSION["errorMsg"] = $ex->getMessage();
}
}
    
asked by anonymous 22.02.2016 / 20:43

1 answer

1

From what I see, you do not return the data at any time. Give this code a try:

$data = array();

try {
   ...

   if ($result > 0) {
       $data["errorType"] = "success";
       $data["errorMsg"] = "Sua mensagem foi enviada com Sucesso.";
   } else {
       $data["errorType"] = "danger";
       $data["errorMsg"] = "Falha ao enviar.";
   }
} catch (Exception $ex) {
   $data["errorType"] = "danger";
   $data["errorMsg"] = $ex->getMessage();
}

echo json_encode($data);
die;

PS: One thing I did not understand was you put the returns on $ _SESSION, it would not be a good idea in this case.

    
22.02.2016 / 21:12