2016-05-29 54 views
0

我可以發送電子郵件並正常獲取,但想要單擊提交按鈕,表單已發送並向用戶顯示一條消息,並繼續在頁面上正常顯示。 Ja試着用ajax和一切都沒有。發送電子郵件並繼續在同一頁面

我希望消息出現在div中,與下圖完全相同。

HTML

<form class="well form-horizontal" action="php/contato.php" method="post" id="contact_form"> 
    <fieldset> 

      <legend style="text-align: center;">Fale conosco</legend> 

     <!-- Nome --> 

     <div class="form-group"> 
      <label class="col-md-4 control-label">Nome</label> 
      <div class="col-md-4 inputGroupContainer"> 
       <div class="input-group"> 
        <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span> 
        <input name="name" placeholder="Nome Completo" class="form-control" type="text" required> 
       </div> 
      </div> 
     </div> 

     <!-- Email--> 
     <div class="form-group"> 
      <label class="col-md-4 control-label">E-Mail</label> 
      <div class="col-md-4 inputGroupContainer"> 
       <div class="input-group"> 
        <span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span> 
        <input name="email" placeholder="E-Mail" class="form-control" type="text" required> 
       </div> 
      </div> 
     </div> 


     <!-- Telefone--> 

     <div class="form-group"> 
      <label class="col-md-4 control-label">Telefones</label> 
      <div class="col-md-4 inputGroupContainer"> 
       <div class="input-group"> 
        <span class="input-group-addon"><i class="glyphicon glyphicon-earphone"></i></span> 
        <input name="telefone" placeholder="(xx)xxxxx-xxxx" class="form-control" type="text" required> </br> 
        <input name="celular" placeholder="Seu Whatsapp (Opcional)" class="form-control" type="text"> 
       </div> 
      </div> 
     </div> 

     <!-- Assunto--> 

     <div class="form-group"> 
      <label class="col-md-4 control-label">Assunto</label> 
      <div class="col-md-4 inputGroupContainer"> 
       <div class="input-group"> 
        <span class="input-group-addon"><i class="glyphicon glyphicon-comment"></i></span> 
        <input name="assunto" placeholder="Assunto" class="form-control" type="text" required> 
       </div> 
      </div> 
     </div> 

     <!-- Mensagem --> 

     <div class="form-group"> 
      <label class="col-md-4 control-label">Deixe-nos sua mensagem.</label> 
      <div class="col-md-6 inputGroupContainer"> 
       <div class="input-group"> 
        <span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span> 
        <textarea class="form-control" name="mensagem" placeholder="Dúvidas, elogios, Criticas ou Sugestões são bem vindas." required></textarea> 
       </div> 
      </div> 
     </div> 

     **<!-- I want the message to appear here -->** 
     <div class="alert alert-success" role="alert" id="success_message">Sucesso <i class="glyphicon glyphicon-thumbs-up"></i> Muito obrigado pelo contato, retornaremos em breve.</div> 

     <!-- Button --> 
     <div class="form-group"> 
      <label class="col-md-4 control-label"></label> 
      <div class="col-md-4"> 
       <button type="submit" class="btn btn-warning">Enviar <span class="glyphicon glyphicon-send"></span></button> 
      </div> 
     </div> 

    </fieldset> 
</form> 

的JavaScript

$(function() { 

    $('#contact_form').validator(); 

    $('#contact_form').on('submit', function (e) { 
     if (!e.isDefaultPrevented()) { 
      var url = "php/contato.php"; 

      $.ajax({ 
       type: "POST", 
       url: url, 
       data: $(this).serialize(), 
       success: function (data) 
       { 
        var messageAlert = 'alert-' + data.type; 
        var messageText = data.message; 

        var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>'; 
        if (messageAlert && messageText) { 
         $('#contact_form').find('.messages').html(alertBox); 
         $('#contact_form')[0].reset(); 
        } 
       } 
      }); 
      return false; 
     } 
    }) 
}); 

contato.php

<?php 

// configure 
$from = 'email'; 
$sendTo = 'email'; 
$subject = 'Contato do site'; 
$fields = array('name' => 'Nome do Cliente', 'email' => 'Email', 'telefone' => 'Telefone', 'celular' => 'Celular', 'assunto' => 'Assunto', 'mensagem' => 'Mensagem'); // array variable name => Text to appear in email 
$okMessage = 'Email enviado, já já entraremos em contato'; 
$errorMessage = 'Ocorreu um erro no envio e ja fomos notificados sobre isso, aperte F5 e tente novamente por favor'; 

// let's do the sending 

try 
{ 
    $emailText = "Mais um contato chegando através do site\n=============================\n"; 

    foreach ($_POST as $key => $value) { 

     if (isset($fields[$key])) { 
      $emailText .= "$fields[$key]: $value\n"; 
     } 
    } 

    mail($sendTo, $subject, $emailText, "From: " . $from); 

    $responseArray = array('type' => 'success', 'message' => $okMessage); 
} 
catch (\Exception $e) 
{ 
    $responseArray = array('type' => 'danger', 'message' => $errorMessage); 
} 

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { 
    $encoded = json_encode($responseArray); 

    header('Content-Type: application/json'); 

    echo $encoded; 
} 
else { 
    echo $responseArray['message']; 
} 
?> 

send email

+0

阿賈克斯救援...... – Poiz

+0

無法測試不知道哪個插件用於'validator()'。所以,檢查錯誤並查看您的控制檯。不知道如果jquery的加載與否。 –

回答

2
... 
$('#contact_form').on('submit', function (e) { 
    if (!e.isDefaultPrevented()) { 
... 

您並未阻止默認操作。

你可能想使用:

... 
$('#contact_form').on('submit', function (e) { 
    // Prevent form submission 
    e.preventDefault(); 
    if (true) { // you no longer need the if-block 
... 
+0

只有此更改發送了表單並且會導致用戶停留在同一頁面上? –

+0

表單對提交的默認操作是重新加載頁面,所以是的,您希望阻止默認操作,而是執行您的AJAX調用。您可以通過將表單的操作設置爲與您的AJAX調用的url不同的url來檢測它,並檢查哪一個被訪問。 –

+0

改變和發佈,超越不工作,因爲重定向到contato.php的頁面電子郵件沒有被解僱,因爲沒有在收件箱裏沒有:(你能告訴我爲什麼嗎? –

1

HTML

<form class="well form-horizontal" action="" method="POST" id="contact_form"> 
     <fieldset> 

      <legend style="text-align: center;">Fale conosco</legend> 

      <!-- Nome --> 

      <div class="form-group"> 
       <label class="col-md-4 control-label">Nome</label> 
       <div class="col-md-4 inputGroupContainer"> 
        <div class="input-group"> 
         <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span> 
         <input name="name" placeholder="Nome Completo" class="form-control" type="text" required> 
        </div> 
       </div> 
      </div> 

      <!-- Email--> 
      <div class="form-group"> 
       <label class="col-md-4 control-label">E-Mail</label> 
       <div class="col-md-4 inputGroupContainer"> 
        <div class="input-group"> 
         <span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span> 
         <input name="email" placeholder="E-Mail" class="form-control" type="text" required> 
        </div> 
       </div> 
      </div> 


      <!-- Telefone--> 

      <div class="form-group"> 
       <label class="col-md-4 control-label">Telefones</label> 
       <div class="col-md-4 inputGroupContainer"> 
        <div class="input-group"> 
         <span class="input-group-addon"><i class="glyphicon glyphicon-earphone"></i></span> 
         <input name="telefone" placeholder="(xx)xxxxx-xxxx" class="form-control" type="text" required> </br> 
         <input name="celular" placeholder="Seu Whatsapp (Opcional)" class="form-control" type="text"> 
        </div> 
       </div> 
      </div> 

      <!-- Assunto--> 

      <div class="form-group"> 
       <label class="col-md-4 control-label">Assunto</label> 
       <div class="col-md-4 inputGroupContainer"> 
        <div class="input-group"> 
         <span class="input-group-addon"><i class="glyphicon glyphicon-comment"></i></span> 
         <input name="assunto" placeholder="Assunto" class="form-control" type="text" required> 
        </div> 
       </div> 
      </div> 

      <!-- Mensagem --> 

      <div class="form-group"> 
       <label class="col-md-4 control-label">Deixe-nos sua mensagem.</label> 
       <div class="col-md-6 inputGroupContainer"> 
        <div class="input-group"> 
         <span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span> 
         <textarea class="form-control" name="mensagem" placeholder="Dúvidas, elogios, Criticas ou Sugestões são bem vindas." required></textarea> 
        </div> 
       </div> 
      </div> 

      <!-- I want the message to appear here --> 
      <div class="alert alert-success" role="alert" id="success_message"> 
       Sucesso <i class="glyphicon glyphicon-thumbs-up"></i> Muito obrigado pelo contato, retornaremos em breve. 
      </div> 

      <!-- Button --> 
      <div class="form-group"> 
       <label class="col-md-4 control-label"></label> 
       <div class="col-md-4"> 
        <button type="submit" class="btn btn-warning">Enviar <span class="glyphicon glyphicon-send"></span></button> 
       </div> 
      </div> 

     </fieldset> 
    </form> 

JAVASCRIPT

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> 
    <script type="text/javascript"> 
     (function ($) { 
      $(document).ready(function (e) { 
       var contactForm = $('#contact_form'); 
       contactForm.on('submit', function (evt) { 
        evt.preventDefault(); 
        var url  = "contato.php"; 
        var objData = { 
         "name"  : $("input[name=name]").val(), 
         "email"  : $("input[name=email]").val(), 
         "telefone" : $("input[name=telefone]").val(), 
         "celular" : $("input[name=celular]").val(), 
         "assunto" : $("input[name=assunto]").val(), 
         "mensagem" : $("input[name=mensagem]").val() 
        }; 

        $.ajax({ 
         type: "POST", 
         url: url, 
         data: objData, 
         success: function (data){ 
          if (data.type && data.message) { 
           var messageAlert = 'alert-' + data.type; 
           var messageText  = data.message; 
           var alertBox  = '<div class="alert ' + messageAlert + ' alert-dismissable">'; 
           alertBox   += '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>'; 
           alertBox   += messageText + '</div>'; 
           contactForm.find('#success_message').html(alertBox); 
           contactForm[0].reset(); 
          } 
         } 
        }); 
        return false; 
       }) 
      }); 
     })(jQuery); 
    </script> 

PHP

<?php 
     header('Access-Control-Allow-Origin: *'); 
     header('Content-Type: application/json'); 

     // PLEASE MAKE SURE YOU DON'T HAVE ANY WHITESPACE BEFORE THE OPENING PHP TAG (<?php) 
     // Por favor, certifique-se de que você não tem qualquer espaço em branco antes da tag de abertura do PHP (<?php) 
     $from   = 'email'; 
     $sendTo   = 'email'; 
     $subject  = 'Contato do site'; 
     $okMessage  = 'Email enviado, já já entraremos em contato'; 
     $errorMessage = 'Ocorreu um erro no envio e ja fomos notificados sobre isso, aperte F5 e tente novamente por favor'; 


     try { 

      // GET & SANITIZE THE POST DATA... 
      $name  = isset($_POST['name'])  ? htmlspecialchars(trim($_POST['name']))  : ""; 
      $email  = isset($_POST['email']) ? htmlspecialchars(trim($_POST['email']))  : ""; 
      $telefone = isset($_POST['telefone']) ? htmlspecialchars(trim($_POST['telefone'])) : ""; 
      $celular = isset($_POST['celular']) ? htmlspecialchars(trim($_POST['celular']))  : ""; 
      $assunto = isset($_POST['assunto']) ? htmlspecialchars(trim($_POST['assunto']))  : ""; 
      $mensagem = isset($_POST['mensagem']) ? htmlspecialchars(trim($_POST['mensagem'])) : ""; 

      // BUILD UP THE MESSAGE... 
      $emailText = "Mais um contato chegando através do site\n=============================\n"; 
      $emailText .= "Nome do Cliente: \n$name\n\n"; 
      $emailText .= "Email: \n$email\n\n"; 
      $emailText .= "Telefone: \n$telefone\n\n"; 
      $emailText .= "Celular: \n$celular\n\n"; 
      $emailText .= "Assunto: \n$assunto\n\n"; 
      $emailText .= "Mensagem: \n$mensagem\n\n"; 

      mail($sendTo, $subject, $emailText, "From: " . $from); 

      $responseArray = array('type' => 'success', 'message' => $okMessage); 
     }catch (\Exception $e){ 
      $responseArray = array('type' => 'danger', 'message' => $errorMessage); 
     } 

     // SIMPLY DIE-OUT THE JSON-ENCODED RESPONSE... 
     die(json_encode($responseArray)); 
    ?> 
+0

我測試了這段代碼,並在用戶重定向到頁面後提交併在屏幕上出現contato.php這個數據{「type」:「success」,「message」:「Email sent,j \ u00e1 j \ u00e1 will contact 「} –

+0

@PauloRoberto現在檢查它...它應該工作...你也應該複製HTML,因爲我們也更新了它...測試它;只需複製所有內容:** HTML,JAVASCRIPT和PHP。**祝您好運,我的朋友..... – Poiz

+0

沒有'Access-Control-Allow-Origin'標題出現在請求的資源上。因此來源不允許訪問。 –

相關問題