【发布时间】:2013-11-18 07:46:25
【问题描述】:
PHP mail() 循环正在运行,并且发送正确,没有错误。但是,我的 jQuery 无法在前端通知成功或错误消息。
PHP:
add_action( 'wp_ajax_invfr_process_ajax', 'invfr_sendmail');
add_action( 'wp_ajax_nopriv_invfr_process_ajax', 'invfr_sendmail');
function invfr_sendmail() {
$post = ( !empty( $_POST ) ) ? true : false;
if( $post ) {
$subject = invfr_get_settings( 'subject' );
$message = invfr_get_settings( 'message' );
$friends = $_POST['friend_email'];
$errors = array();
foreach ( $friends as $key => $friend ) {
$name = stripslashes( $_POST['friend_name'][$key] );
$email = trim( $_POST['friend_email'][$key] );
// Check name
if( !$name )
$errors[] = '#friend_name-' . $key;
if( !$email )
$errors[] = '#friend_email-' . $key;
if( $email && !is_email( $email ) )
$errors[] = '#friend_email-' . $key;
}
// send email
if( !$errors ) {
foreach ( $friends as $key => $friend )
$mail = wp_mail( $email, invfr_tokens_replacement( $subject, $_POST, $key ), invfr_tokens_replacement( $message, $_POST, $key ) );
if( $mail )
echo 'sent';
}
else
echo json_encode( $errors );
}
}
jQuery:
<script type="text/javascript">
var jQuery = jQuery.noConflict();
jQuery(window).load(function(){
jQuery('#invfr_form').submit(function() {
// change visual indicators
jQuery('td').removeClass('error');
jQuery('.loading').show();
jQuery('.submit input').attr('disabled', 'disabled');
// validate and process form here
var str = jQuery(this).serialize();
jQuery.ajax({
type: 'POST',
url: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
data: str,
success: function(msg) {
jQuery('#invfr_note').ajaxComplete(function(event, request, settings) {
msg = msg.replace(/(\s+)?.$/, "");
if( msg == 'sent' ) {
result = '<div class="updated"><p><?php _e( 'Your invitation has been sent! Send another?', 'invfr' ); ?></p></div>';
jQuery('#invfr_form input[type=text], #invfr_form input[type=email]').val('');
} else {
//loop through the error items to indicate which fields have errors
msg = msg.replace(/[\[\]']+/g,'');
msg = msg.split(',');
jQuery.each( msg, function ( i, id ) {
id = id.replace(/["']{1}/g, '');
jQuery(id).parent('td').addClass('error');
});
result = '<div class="error"><p><?php _e( '<strong>ERROR:</strong> Check your form for the errors which are highlighted below.', 'invfr' ); ?></p></div>';
//result = msg;
msg = '';
}
jQuery(this).html(result);
// visual indicators
jQuery('.loading').hide();
jQuery('.submit input').removeAttr('disabled');
});
}
});
return false;
});
});
</script>
感谢您的帮助!
【问题讨论】:
-
您确定它不会进入您没有收听的错误回调吗?你为什么在 ajax 成功的内部使用 ajaxComplete?
-
因为我不是一个优秀的程序员?这是我最好的答案。我已经在这个东西上颠簸了 3 个小时,无法让该死的加载 gif 停止旋转并给我一个成功的警报。
-
添加错误回调,类似于你的成功回调。
error: function(){ console.log(arguments) } -
只有状态码不是200的时候才会发生错误回调,与PHP脚本回显的内容无关。
-
ajaxComplete 方法正在注册一个处理程序,以便在 ajax 请求完成时调用。但是,由于您在 success 方法中,因此 ajax 请求已经完成。因此,完整函数中的任何代码都不会执行
标签: php jquery wordpress email