Wordpress ajax成功回应

时间:2014-10-16 19:59:01

标签: javascript jquery ajax wordpress

我正在尝试使用wp_mail和Ajax

在Wordpress中创建联系表单

电子邮件有效,但我遇到了Ajax成功响应问题。

发送电子邮件后,我需要向用户显示电子邮件已发送的消息。

用于验证表单并显示成功消息的Javascript:

    $atj(function(){
      $atj('#training-submit').click(function(e) {
        e.preventDefault();
        e.stopPropagation();
        if(verfiyFields()) {
            alert('here');
            requestData = {
              'action' : 'myajax-submit',
              'firstName' : $atj("#name").val(), 
              'email' : $atj("#email").val(), 
          }
          $atj.post(MyAjax.ajaxurl, requestData).done(function(result){        
            result = jQuery.parseJSON( result );
            console.log(result);
            if(result == 'success'){
              $atj('.training-form [type=text]').val('');
              $atj('.training-form-message').append('<p class="training-form-complete-message">Thank you for the  email</p>');
            }
          });
        }
      });
    })



    //Verfiy 
    function verfiyTrainingFields() {
      var flag = true;

      var name =        $atj('#name');
      var email =       $atj('#email');

      if(name.val().indexOf(' ') === -1 ){
        name.parent().prepend('<p class="form-error">Please enter name, first space last</p>');
        errorMessage($atj('.form-error'));
        flag = false;
      }
      if(!IsEmail(email.val())){
        email.parent().prepend('<p class="form-error">Please enter valid email address</p>');
        errorMessage($atj('.form-error'));
        flag = false;
      }
      return flag;
    }

发送电子邮件并发送ajax响应的functions.php文件。

    function myajax_submit() {

        $name = sanitize_text_field($_POST['firstName']);
        $email = sanitize_text_field($_POST['email']);

        $headers[] = 'From: ' . $name . ' <' . $email . '>' . "\r\n";
        $headers[] = 'Content-type: text/html' . "\r\n"; //Enables HTML ContentType. Remove it for Plain Text Messages

        $to = 'me@mysite.co.uk';

        $message = 'Name: ' . $name . "\r\n" . 'email: ' . $email;

        add_filter( 'wp_mail_content_type', 'set_html_content_type' );
        wp_mail( $to, 'Email Test', $message );
        remove_filter( 'wp_mail_content_type', 'set_html_content_type' ); 

        echo 'email sent';

        // generate the response
        $response = json_encode( array( 'success') );

        // response output
        header( "Content-Type: application/json" );
        echo $response;

        exit;
    }

发送电子邮件并发送'email sent'回显,但js中的if(result == 'success'){无效。

js文件中的console.log(result)给出以下内容。

<br />
<b>Warning</b>:  call_user_func_array() expects parameter 1 to be a valid callback, function 'set_html_content_type' not found or invalid function name in <b>/Users/user.name/Desktop/MAMP-DocRoot/appname/src/php/wp-includes/plugin.php</b> on line <b>192</b><br />
email sent<br />
<b>Warning</b>:  Cannot modify header information - headers already sent by (output started at /Users/user.name/Desktop/MAMP-DocRoot/appname/src/php/wp-includes/plugin.php:192) in <b>/Users/user.name/Desktop/MAMP-DocRoot/appname/src/php/wp-content/themes/sitename/functions.php</b> on line <b>66</b><br />
["success"] 

2 个答案:

答案 0 :(得分:0)

您无法在回复后设置headers。除掉 echo 'email sent';

答案 1 :(得分:0)

首先,删除echo语句,因为它过早地发送标题。

然后,你需要明确地告诉jQuery帖子期待json:

$atj.post(MyAjax.ajaxurl, requestData).done(function(result){
    result = jQuery.parseJSON( result );
    console.log(result);
    if(result == 'success'){
        $atj('.training-form [type=text]').val('');
        $atj('.training-form-message').append('<p class="training-form-complete-message">Thank you for the  email</p>');
    }
}, 'json' );

最后,您的json编码响应不会为您提供预期的response == success。相反,请使用json_encode( array( 'success' => 1' ) );并将您的javascript更改为:

if( 1 == result.success ) ){
}

这是一个完整的例子:

$.post( url, data, function( response ){
    if( 1 == response.success ){
      // Success - do something
    } else {
      // Failure
    }
}, 'json' );

<?php
function myAjaxFunction(){
    $result = array(
        'success' => 0 // Assume failure first
    );
    if( $_POST[ 'whatever' ] == 'what i want' ){
        $result[ 'success' ] = 1;
    }
    print json_encode( $result );
    exit();
}