【发布时间】:2014-10-18 03:38:28
【问题描述】:
我一直在尝试使用 Mandril 从 Web 表单发送一封简单的电子邮件。我可以从他们的 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;
}
?>
【问题讨论】:
-
检查答案。
$_POST('params')上的问题
标签: php jquery ajax email mandrill