【问题标题】:Ajax and Sending FormsAjax 和发送表单
【发布时间】:2014-03-22 14:35:43
【问题描述】:

我在从我的实时站点发送邮件时遇到问题。

奇怪的是,当我禁用 JavaScript 时,邮件会正确发送(我在收件箱中收到)。

当我启用 JavaScript 并尝试使用 Ajax 发送它时,Ajax 返回成功,因为我收到了“谢谢,您的邮件已发送”的自定义消息(尽管它从未发送过)出现。因为我得到了成功返回,所以我必须假设处理脚本运行没有错误。仍然,启用 JavaScript 时邮件不会发送。

这是我的 ajax 调用:

if(success == false) {
        if(event.preventDefault) {
            event.preventDefault();
        }
    } else {
        event.preventDefault();

        $.ajax('mailprocess.inc.php', {
            type: "POST",
            data: form.serialize(),
            success: function() {
                var formWrapper  = $('.form-wrapper');
                var confirmMessageSection = $("<section class=\"confirm-message\"></section>");
                formWrapper.empty().append(confirmMessageSection);
                confirmMessageSection.html("<p>Thank you! Your message has been sent.</p>").hide().fadeIn(1500);            
            },
            error: function(request, errorType, errorMessage) {
                var formWrapper = $('.form-wrapper');
                var errorMessageSection = $("<section class=\"email-error\"></section>");
                formWrapper.empty().append(errorMessageSection);
                errorMessageSection.html("<p>Sorry, there was an error.</p><p>Request error type: " + request + "</p><p>Error type: " + errorType + "</p><p>Error Message: " + errorMessage + "</p>").hide().fadeIn(1500);  
            },
            timeout:5000,
            beforeSend: function() {
                //add spinner
                $('.form-wrapper').empty().addClass('is-loading');
            },
            complete: function() {
                //remove spinner
                $('.form-wrapper').removeClass('is-loading');
            }
        });
     }

这是我的处理脚本的第一部分(在我的 contact.php 文件的顶部):

<?php

//set up arrays for processing script

$errors = array();
$missingInputs = array();
if(isset($_POST['send'])) {
//parameters for mail() function
    $to = "mail@server.com";
    $subject = "Message";

    //fields expected
    $expectedFields = array('name', 'email', 'comments');
    //required fields
    $requiredFields = array('name', 'email', 'comments');

    $mailHeaders = "From: The site <me@mysite.com>\r\n";
    $mailHeaders .= 'Content-Type: text/plain; charset=utf-8';

    require 'mailprocess.inc.php';


}
?>

这是我的处理脚本:

<?php
//for now, nothing the user has inputted is suspicious
$suspicious = false;
$pattern = '/Content-Type:|Bcc:|Cc:/i';

//this checks for suspicious phrases
function isSuspicious($val, $pattern, &$suspicious) {
    if(is_array($val)) {
        foreach ($val as $item) {
            isSuspicious($item, $pattern, $suspicious);
        }
    } else {
        if(preg_match($pattern, $val)) {
            $suspicious  = true;
        }
    }
}

isSuspicious($_POST, $pattern, $suspicious);

if($suspicious == false) {
    foreach ($_POST as $nameAttributeValue => $userInputtedValue) {
        //take user input (ex. their name they typed in the form) and store it into a variable called $temp
        if(is_array($userInputtedValue)) {
            $temp = $userInputtedValue;
        //if user input is not an array, strip out whitespace first
        } else {
            $temp = trim($userInputtedValue);
        }

        //if the user left the field open and it's required (they all are), add the "key" ("name", "email", "comments") to the missing array
        if(empty($temp) && in_array($nameAttributeValue, $requiredFields)) {
            $missingInputs[] = $nameAttributeValue;
        //if the user filled out the field, assign the name attribute value ("name", "email" or "comments") to a variable of the same name as itself (ie. if it's 'name', the variable will be $name)
        } elseif(in_array($nameAttributeValue, $expectedFields)) {
            ${$nameAttributeValue} = $temp;
        }
    }
}

if(!$suspicious && !empty($email)) {
    $validEmail = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
    if($validEmail) {
        $mailHeaders .= "\r\nReply-To: $validEmail";
    } else {
        $errors['email'] = true;
    }
}


$sentMail = false;

if(!$suspicious && !$missingInputs && !$errors) {
    $message = '';
    foreach ($expectedFields as $item) {
        if(isset(${$item}) && !empty(${$item})) {
            $val = ${$item};
        } else {
            $val = 'Not selected';
        }
        if(is_array($val)) {
            $val = implode(', ' ,$val);
        }
        $item = str_replace(array('_', '-'), ' ', $item);
        $message .= ucfirst($item) . " : $val\r\n\r\n";
        $message = wordwrap($message, 70);
    }   




    $sentMail = mail($to, $subject, $message, $mailHeaders);
    if(!$sentMail) {
        $errors['mailNotSent'] = true;
    }

}

?>

有什么想法吗?我很困惑。

编辑:

console.logging我根据第一个答案从成功中返回的数据后,我得到了这个错误:

Warning: in_array() expects parameter 2 to be array, null given in /home/mailprocess.inc.php on line 36

所以我将数组移到邮件处理文件中,不再收到该错误。事实上,console.log(data) 返回空白。邮件说它仍然是通过 Ajax 发送的,但它仍然不是。

【问题讨论】:

  • 如果您找到了这个问题的答案,请将其添加为这个问题的答案(并且只是一个答案)。无需编辑您的问题以包含答案。

标签: javascript php jquery ajax email


【解决方案1】:

对不起,亲爱的你使用了太多复杂的代码试试这个:

index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<title>Jquery Mail</title>

<script type="text/javascript">
$(document).ready(function(e) {
$('#send').click(function()
{
    $.ajax({
    type:'POST',
    url:"mail.php",
    data:"name="+$('#name').val()+"&email="+$('#email').val()+"&phone="+$('#phone').val()+"",
    async:false,
    success: function(result)
    {
        alert(result);
    }
});
})

   });
</script>
</head>

<body>
<table width="500" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td colspan="5" align="center">Mail Form</td>
</tr>
<tr>
<td width="119">&nbsp;</td>
<td width="86">&nbsp;</td>
<td width="246">&nbsp;</td>
<td width="23">&nbsp;</td>
<td width="26">&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>Name:</td>
<td><input type="text" name="textfield" id="name" /></td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>Email</td>
<td><input type="text" name="textfield2" id="email" /></td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>Phone:</td>
<td><input type="text" name="textfield3" id="phone" /></td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td><input type="submit" name="button" id="send" value="Send" /></td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
</table>
</body>
</html>

邮件.php

<?php
if(isset($_POST['name']))
{
$name=$_POST['name'];
$email=$_POST['email'];
$phone=$_POST['phone'];

/*

Here You Can Set your mail Function


*/

echo "Entered Name= ".$name.", Entered Email= ".$email.", Entered Phone= ".$phone;
}
?>

【讨论】:

    【解决方案2】:

    你能用这个替换你的成功函数吗:

    console.log(form.serialize()) ;
     $.ajax('mailprocess.inc.php', {
            type: "POST",
            data: form.serialize(),
            success: function(data) {
                console.log(data) ;
    

    它会首先在控制台中显示提交的内容,只是为了检查它是否正确,然后在 ajax 中调用你的 php 文件的输出。

    您收到“谢谢!您的..”消息的事实仅意味着您的 php 文件可以通过 ajax 调用(没有 404 或 500 错误),但您不知道其他任何内容,比如有什么问题在 php 代码上......或者其他)

    【讨论】:

    • 啊,好吧。我在日志中收到错误。在我的 in_array 方法中获取 null ......但这似乎不对,因为 PHP 服务器端验证正在工作。它也在禁用 JS 的情况下发送。 form.serialize() 返回预期的结果。因此,这可能与将值传递到脚本中的方式有​​关。
    • 澄清我的想法:错误是“警告:in_array() 期望参数 2 是数组,在第 36 行的 /home/mailprocess.inc.php 中给出 null” - 所以错误在PHP 文件 - 但是在没有启用 JS 的情况下发送邮件时这有什么意义呢?如果是 PHP 文件问题,则根本不应该发送邮件。
    猜你喜欢
    • 1970-01-01
    • 2016-11-25
    • 1970-01-01
    • 2011-08-09
    • 2016-09-30
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多