Error returning AJAX data

Asked

Viewed 31 times

0

My code is working up to the point where the ajax has to pick up the answer to print on the screen, the Insert is being done normally in the comic, if I change the return $("#requests"). html(data); to $("#requests"). html(data); works by returning serialize, something is 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();
}
}
  • 1

    I don’t understand what the problem is.

  • updated page and not return on div id="orders"

  • the date will return with whatever comes from the.php requests, in the code I have not seen what you are wanting to print

1 answer

1


From what I see you do not return the data at any time. Gives a tested in this code:

$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 didn’t understand was you putting the returns on $_SESSION, it wouldn’t be a good idea in this case.

  • look what retouched = {"errorType":"Success","errorMsg":"Your message was sent successfully."} as for the use of $_Session I thought it was safer since the page and external

  • 1

    Now you handle this in your JS. You can catch the type of error in the callback of Success (data.errorType) and so on.

Browser other questions tagged

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