我一直在尝试使用Mandril从网络表单发送一封简单的电子邮件。我可以从他们的api文档中使用mandrill的PHP示例收到一封电子邮件。
然而,当我尝试通过jQuery的.ajax函数传入一个json对象时,Mandrill给了我这个错误:
Fatal error: Function name must be a string in /home4/kknopper/public_html/mandrill.php on line 5
我刚开始使用.ajax,我觉得这可能是一个非常简单的修复。 任何帮助将不胜感激!
JS:
//This all runs when the user submits the form
var email = $("#email").val(); // get email field value
var name = $("#fname").val(); // get name field value
var format = "- ";
var fname = format + name;
var message = $("#message").val(); // get message field value
message = message + "\n\n"+fname;
function log(obj) {
console.log(JSON.stringify(obj));
}
var params = {
"message": {
"from_email": email,
"to":[{"email":"email@gmail.com"}],
"subject": "Web Contact Form Response",
"text": message
}
};
console.log(params);
var formReset = function() {
$("#fname").val(''); // reset field after successful submission
$("#email").val(''); // reset field after successful submission
$("#message").val(''); // reset field after successful submission
$("form input").attr("class","ng-pristine ng-invalid ng-invalid-required");
$("form textarea").attr("class","ng-pristine ng-invalid ng-invalid-required");
$("form button").attr("disabled","disabled");
};
$.ajax(
{
type: "POST",
url: "mandrill.php",
data: JSON.stringify(params)
})
.done(function(response) {
alert(response);
console.log(response);
// show success message
formReset(); // reset field after successful submission
})
.fail(function(response) {
alert('Error sending message.');
return false; // prevent page refresh
})
.success(function(data) {
console.log(data);
console.log(data[0].status);
alert('Your message has been sent. Thank you!');
if (!data.success) {
// if not successful, bind errors to error variables
// $scope.errorName = data.errors.name;
// $scope.errorSuperhero = data.errors.superheroAlias;
} else {
// if successful, bind success message to message
$scope.message = data.message;
}
});
mandrill.php:
<?php
require_once 'mandrill-api-php/src/Mandrill.php';
try {
$mandrill = new Mandrill('my api key');
$input = json_encode($_POST('params'));
//If I pass in this message variable the email sends.
// $message = array(
// 'text' => $input.message.text,
// 'subject' => 'Web Contact Form',
// 'from_email' => $_POST["params.message."],
// 'from_name' => 'Example Name',
// 'to' => array(
// array(
// 'email' => 'email@gmail.com',
// 'name' => 'Recipient Name',
// 'type' => 'to'
// )
// )
// );
$async = false;
$result = $mandrill->messages->send($input, $async);
print_r($result);
} catch(Mandrill_Error $e) {
// Mandrill errors are thrown as exceptions
echo 'A mandrill error occurred: ' . get_class($e) . ' - ' . $e->getMessage();
throw $e;
}
?>
答案 0 :(得分:0)
查看您发送到后端的JSON,我们可以看到:
{
message: {
...
}
}
但在第5行:
$input = json_encode($_POST('params'));
您正在使用帖子数据中实际不存在的params
索引来访问它。正确的索引是message
。
EDITED: 除此之外,错误与您访问数组$ _POST的方式有关。您应该使用括号[]来使用括号来索引$ _POST变量。使用括号,PHP尝试调用$ _POST中字符串表示的函数,该函数不是字符串。