简体   繁体   English

Php表单ajax“成功与失败”消息

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

The form on my website is a simple contact form.我网站上的表格是一个简单的联系表格。 I would like the form to show a "success & failed" message on the same page when the form is sent/failed without reloading the page.当表单发送/失败而不重新加载页面时,我希望表单在同一页面上显示“成功和失败”消息。 I understand that I should use Ajax to do this but I can't get it to work because my knowledge about it is very little.我知道我应该使用 Ajax 来做到这一点,但我无法让它工作,因为我对它的了解很少。

Here is the code I'm working with.这是我正在使用的代码。

Html (single page design): 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:博士:

<?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";
    }
?>

Your Ajax call is not working properly.您的Ajax调用工作不正常。 Try this试试这个

$(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();
                    }
                });
            });
        });

Also as you can see i have used $('#contactus').serialize() this way you dont need to pass the form elements one by one instead serialize() will pass the whole form elements to your php page同样如您所见,我使用了$('#contactus').serialize()这样您就不需要一个一个地传递表单元素,而是serialize()将整个表单元素传递给您的 php 页面

Than in your php file echo successful if everything went well else echo error if the response is an error than show the error div比你的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";
    }
?>

Change your PHP script like this:像这样更改你的 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 Edit 2020 编辑

In REST API response should be always accompanied by the correct HTTP status code, with 200+ telling client that request ended up correctly processed or was otherwise good, 400+ telling client there was an error in request, and 500+ that there was a problem with the server itself.在 REST API 响应中应该始终伴随正确的 HTTP 状态代码,200+ 告诉客户端请求最终被正确处理或其他方面很好,400+ 告诉客户端请求中有错误,500+ 告诉客户端有问题与服务器本身。 Do not use statuses inside responses, it is unnecessary duplication of the existing feature:不要在响应中使用状态,这是对现有功能的不必要重复:

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

exit;

Then you can handle request and response with jQuery(assuming that you still use jQuery):然后你可以使用 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
  });
;

If you need specific status, you can get it from jqXHR parameter using jqXHR.status field.如果您需要特定状态,您可以使用jqXHR.status字段从jqXHR参数中获取它。

Original answer原答案

You can use dataType: 'json' in your ajax call.您可以在ajax调用中使用dataType: 'json'

Then you'll be able to pass status code as response key:然后您就可以将状态代码作为响应键传递:

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

echo json_encode($response);

In js then you can check data.success === 'ok' to know what's your status.在 js 中,您可以检查data.success === 'ok'以了解您的状态。

In your php script you could try this在你的 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