Campaign Monitor Ajax表单提交

时间:2018-07-25 22:26:25

标签: javascript ajax campaign-monitor

广告系列监控器似乎已更新了其代码段,以使用另一种提交表单的方法。现在,在extends React.PureComponent标记中有一个<form>属性。不再有使用Ajax提交表单的常用方法。有人知道如何使用Ajax提交新样式的Campaign Monitor表单吗?

以下是Campaign Monitor给我的代码片段:

data-id

1 个答案:

答案 0 :(得分:2)

我通过电子邮件发送了他们的支持,因此我可以自己回答问题。他们已将所有旧方法替换为其API。您需要将表单的操作设置为自己的端点(例如signup.php)。

我正在使用PHP,因此我从https://github.com/campaignmonitor/createsend-php下载了他们的PHP API包装器。一个简单的例子是这样的:

require_once 'lib/campaignmonitor/csrest_subscribers.php';

$auth = array(
    'api_key' => 'Your API key'
);
$wrap = new CS_REST_Subscribers( 'Your list ID', $auth );

$result = $wrap->add( array(
    'EmailAddress' => 'Subscriber email',
    'Name' => 'Subscriber name',
    'CustomFields' => array(
        array(
            'Key' => 'Field 1 Key',
            'Value' => 'Field Value'
        ),
        array(
            'Key' => 'Field 2 Key',
            'Value' => 'Field Value'
        ),
        array(
            'Key' => 'Multi Option Field 1',
            'Value' => 'Option 1'
        ),
        array(
            'Key' => 'Multi Option Field 1',
            'Value' => 'Option 2'
        )
    ),
    'ConsentToTrack' => 'yes',
    'Resubscribe' => true
) );

更新:如果您好奇的话,这是我完整的PHP:

require_once 'libs/campaignmonitor/csrest_subscribers.php';

$success_message = 'You\'ve been signed up for our email list.';
$error_message_general = 'There was a problem signing you up for the email list. Please try again.';
$error_message_format = 'Please enter a valid email address.';

if ( $_SERVER[ 'REQUEST_METHOD' ] !== 'POST' ) {
    renderResponse( true, $error_message_general );
}
else {

    $api_key = 'your_api_key_here';
    $list_id = 'your_list_id_here';

    $email = array_key_exists( 'email', $_POST ) ? $_POST[ 'email' ] : '';
    $email = cleanInput( $email );

    if ( filter_var( $email, FILTER_VALIDATE_EMAIL ) ) {
        try {
            $auth = array(
                'api_key' => $api_key
            );
            $wrap = new CS_REST_Subscribers( $list_id, $auth );

            $result = $wrap->add( array(
                'EmailAddress' => $email,
                'ConsentToTrack' => 'yes',
                'Resubscribe' => true
            ) );

            if ( $result->was_successful() )
                renderResponse( false, $success_message );
            else
                renderResponse( true, $error_message_general );
        }
        catch ( Exception $e ) {
            renderResponse( true, $error_message_general );
        }
    }
    else {
        renderResponse( true, $error_message_format );
    }

}

function renderResponse( $error, $message ) {
    header( 'Content-Type: application/json' );
    $result = [
        'error' => $error,
        'message' => $message
    ];
    echo json_encode( $result );
    die();
}

function cleanInput( $data ) {
    $data = trim( $data );
    $data = stripslashes( $data );
    $data = htmlspecialchars( $data );
    return $data;
}