我使用bellow html代码使用mailchimp API在我的mailchimp帐户列表中提交用户电子邮件。
表格代码:
.....
<form id="signup-form" action="php/newsletter-subscribe.php" method="post">
<input type="email" name="email" id="email" placeholder="Email Address" />
<br>
<input type="submit" value="Go!" onclick="wating()" />
</form>
......
newsletter-subscribe PHP代码:
require_once 'mailchimp/MailChimp.php';
use \DrewM\MailChimp\MailChimp;
// Email address verification
function isEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
if($_POST) {
$mailchimp_api_key = 'xxxxxxxxxxxxxxxxxxxxx-xx'; // enter your MailChimp API Key
$mailchimp_list_id = 'xxxxxxxxxx'; // enter your MailChimp List ID
$subscriber_email = addslashes( trim( $_POST['email'] ) );
if( !isEmail($subscriber_email) ) {
echo '<script type="text/javascript">swal("Error!", "Please try again.", "error")</script>';
} else {
$array = array();
$MailChimp = new MailChimp($mailchimp_api_key);
$result = $MailChimp->post("lists/$mailchimp_list_id/members", [
'email_address' => $subscriber_email,
'status' => 'subscribed',
]);
if($result == false) {
$array = '<script type="text/javascript">swal("Error!", "Please try again.", "error")</script>';
} else {
$array = '<script type="text/javascript">swal("Great!", "Your email has been subscribed", "success")</script>';
}
echo json_encode($array);
}
}
问题是在我提交表单后我得到空白页而没有任何错误日志,并且电子邮件已添加到我的mailchimp帐户而没有任何错误。
我尝试使用echo javascript in line 22, 35 and 38
之类的其他java脚本警报更改alert("Text Here");
,除了我得到同样的内容空白页
如何解决此问题并在同一html表单页面中回显javascript警报而不重定向到空白页?
答案 0 :(得分:1)
首先你要设置:
$array = array();
但是稍后,你会这样做:
if($result == false) {
$array = '<script type="text/javascript">swal("Error!", "Please try again.", "error")</script>';
} else {
$array = '<script type="text/javascript">swal("Great!", "Your email has been subscribed", "success")</script>';
}
echo json_encode($array);
换句话说,您正在将数组更改为字符串。 尝试将代码更改为:
if($result == false) {
$array = array('<script type="text/javascript">swal("Error!", "Please try again.", "error")</script>');
} else {
$array = array('<script type="text/javascript">swal("Great!", "Your email has been subscribed", "success")</script>');
}
echo json_encode($array);
另外,我会避免在那里使用<script type="text/javascript">
,我只会返回一个正确的json响应。然后,使用ajax(jquery)调用此文件,解码json并显示警报。
也许这样的事情会给你一个想法: http://labs.jonsuh.com/jquery-ajax-php-json/