簡體   English   中英

Php表單ajax“成功與失敗”消息

[英]Php form ajax “success & fail” message

我網站上的表格是一個簡單的聯系表格。 當表單發送/失敗而不重新加載頁面時,我希望表單在同一頁面上顯示“成功和失敗”消息。 我知道我應該使用 Ajax 來做到這一點,但我無法讓它工作,因為我對它的了解很少。

這是我正在使用的代碼。

Html(單頁設計):

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js"></script>

<form class="form" id="contactus" action="" method="post" accept-charset="UTF-8">




                        <label for="nametag">Namn<FONT COLOR="#FF0060">*</FONT></label>

                        <input name="name" type="text" id="name"  value="" />




                        <label for="emailtag">Email<FONT COLOR="#FF0060">*</FONT></label>

                        <input name="email" type="text" id="email"  value="" />


                        <label for="phonetag">Telefon</label>

                        <input name="phone" type="text" id="phone"  value="" />


                        <label for="messagetag">Meddelande<FONT COLOR="#FF0060">*</FONT></label></br>

                        <textarea name="message" id="message" style="width: 87%; height: 200px;"></textarea>






<label class="placeholder">&nbsp;</label>

                        <button class="submit" name="submit">Skicka</button>



                </form> 



<script>        
    $(function() {
            $('#contactus').submit(function (event) {
                event.preventDefault();
                event.returnValue = false;
                $.ajax({
                    type: 'POST',
                    url: 'php/mail.php',
                    data: $('#contactus').serialize(),
                    success: function(res) {alert(res);
                        if (res == 'successful') {
                            $('#status').html('Sent').slideDown();
                        }
                        else {
                            $('#status').html('Failed').slideDown();
                        } 
                    },
                    error: function () {
                        $('#status').html('Failed').slideDown();
                    }
                });
            });
        });
    </script>   

博士:

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $message = $_POST['message'];
    $recipient = "info@mydomain.com";
    $subject = "Webbkontakt";
    $formcontent = "Från: $name <br/> Email: $email <br/> Telefon: $phone <br/> Meddelande: $message";

    $headers = "From: " ."CAMAXON<info@mydomain.com>" . "\r\n";
    $headers .= "Reply-To: ". "no-reply@mydomain.com" . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=utf-8\r\n";

    if(mail($recipient, $subject, $formcontent, $headers))
    {
        echo "successful";
    }
    else
    {
        echo "error";
    }
?>

您的Ajax調用工作不正常。 試試這個

$(function() {
            $('#contactus').submit(function (event) {
                event.preventDefault();
                event.returnValue = false;
                $.ajax({
                    type: 'POST',
                    url: 'php/mail.php',
                    data: $('#contactus').serialize(),
                    success: function(res) {
                        if (res == 'successful') {
                            $('#status').html('Sent').slideDown();
                        }
                        else {
                            $('#status').html('Failed').slideDown();
                        } 
                    },
                    error: function () {
                        $('#status').html('Failed').slideDown();
                    }
                });
            });
        });

同樣如您所見,我使用了$('#contactus').serialize()這樣您就不需要一個一個地傳遞表單元素,而是serialize()將整個表單元素傳遞給您的 php 頁面

比你的PHP文件echo successful ,如果一切順利,否則echo error如果響應是一個error比秀error div

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $message = $_POST['message'];
    $recipient = "info@mydomain.com";
    $subject = "Webbkontakt";
    $formcontent = "Från: $name <br/> Email: $email <br/> Telefon: $phone <br/> Meddelande: $message";

    $headers = "From: " ."CAMAXON<info@mydomain.com>" . "\r\n";
    $headers .= "Reply-To: ". "no-reply@mydomain.com" . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

    if(mail($recipient, $subject, $formcontent, $headers))
    {
        echo "successful";
    }
    else
    {
        echo "error";
    }
?>

像這樣更改你的 PHP 腳本:

<?php
if( isset( $_POST['submit'] )){ //checking if form was submitted
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$formcontent="Meddelande: \n\n $message";
$recipient = "info@mydomain.com";
$subject = "Webbkontakt";
$mailheader = "Från: $name \n Email: $email \n Telefon: $phone \r\n";

$mailsent = mail($recipient, $subject, $formcontent, $mailheader);

if($mailsent) echo "Success"; //success if mail was sent
else echo "Ett fel uppstod!";
}
?>

在您的mail()函數下方,只需執行echo "successful";

2020 編輯

在 REST API 響應中應該始終伴隨正確的 HTTP 狀態代碼,200+ 告訴客戶端請求最終被正確處理或其他方面很好,400+ 告訴客戶端請求中有錯誤,500+ 告訴客戶端有問題與服務器本身。 不要在響應中使用狀態,這是對現有功能的不必要重復:

http_response_code(200);
echo json_encode(['message' => 'Email was sent']);

exit;

然后你可以使用 jQuery 處理請求和響應(假設你仍然使用 jQuery):

$.ajax({
  url: url,
  data: data,
  dataType: 'json'
})
  .then(function (data, textStatus, jqXHR) {
    // Your 200+ responses will land here
  })
  .fail(function (jqXHR, textStatus, errorThrown) {
    // Your 400+ responses will be caught by this handler
  });
;

如果您需要特定狀態,您可以使用jqXHR.status字段從jqXHR參數中獲取它。

原答案

您可以在ajax調用中使用dataType: 'json'

然后您就可以將狀態代碼作為響應鍵傳遞:

// form response array, consider it was success
$response = array( 'success'=> 'ok', 'message' => 'Email was sent');

echo json_encode($response);

在 js 中,您可以檢查data.success === 'ok'以了解您的狀態。

在你的 php 腳本中,你可以試試這個

if(mail($recipient, $subject, $formcontent, $mailheaders))
{
  echo("Mail Sent Successfully"); // or echo(successful) in your case
}else{
  echo("Mail Not Sent"); // or die("Ett fel uppstod!");

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM