curl_exec 使用 AJAX 时 Mailchimp 不起作用

curl_exec to Mailchimp doesn't work when using AJAX

我在 Wordpress 中创建了一个表单,使用 Mailchimp API 将数据发布到 Mailchimp。如果我只使用一个常规的表单,并带有一个转到适当页面的操作,它就可以正常工作;所有数据都按预期导入。

但是,我想通过 AJAX POST 命令来完成。我发送的信息与使用传统邮寄表格发送的信息相同,但它不起作用。 AJAX 成功条件触发以显示页面已成功加载,因此该页面中一定有某些内容无法正常工作。

这是我的表格:

<div class="card full">
    <form id="mailchimp_actions" method="post" action="/ajax-curl-actions/">
        <select name="action" id="action">
            <option>Subscribe</option>
            <option>Unsubscribe</option>
            <option>Find</option>
        </select>
        <textarea name="import_data" id="import_data" placeholder="Email Address,First Name,Last Name"></textarea>
        <input type="submit">
    </form>
</div>

这是它发布到的页面:

<?php 

    // Template Name: AJAX - cURL actions.

    $subscribers = bfm_data_format($_POST);

    $final_report = array('successes'=>0,'failures'=>array());

    foreach($subscribers as $subscriber) :
        $post_data = array('email' => $subscriber[0], 'fname' =>  $subscriber[1], 'lname' =>  $subscriber[2]);
        $action = $_POST['action'];
        if(!bfm_subscriber_exists($subscriber[0]) && $action=='Subscribe') $action = 'Add New Subscriber';
        $report = bfm_curl_actions(bfm_list_id(),bfm_api_key(),$post_data,$action);     
        if($report['success']) :
            $final_report['successes']++;   
        else:
            $final_report['failures'][] = $report['error'];
        endif;
    endforeach;

?>

<h1>Import Completed</h1>
<p><?=$final_report['successes']?> records were imported successfully.</p>
<h2>Failed imports</h2>
<table>
    <tr>
        <th>Email</th>
        <th>Reason</th>
    </tr>
    <?php foreach($final_report['failures'] as $failure): ?>        
        <tr>
            <td><?=$failure['email']?></td>
            <td><?=$failure['message']?></td>
        </tr>
    <?php endforeach; ?>
</table>

以下是使其工作的各种功能:

<?php   

    function bfm_fudge_timeout(){

        $wpmetetxt = "
        # WP Maximum Execution Time Exceeded
        <IfModule mod_php5.c>
            php_value max_execution_time 10000
        </IfModule>";


        $htaccess = ABSPATH .'/.htaccess';
        $contents = @file_get_contents($htaccess);
        if(!strpos($htaccess,$wpmetetxt))
        file_put_contents($htaccess,$contents.$wpmetetxt);
    }


    add_action("after_switch_theme", "bfm_fudge_timeout");

    // Format data

    function bfm_data_format($data) {
        $import_data = $data['import_data'];
        $import_data_lines = explode("\n",$import_data);
        $i=0;
        foreach($import_data_lines as $import_data_line) :
            $import_data_lines[$i] = explode(',',$import_data_line);
            $i++;
        endforeach;
        return $import_data_lines;
    }

    // MailChimp data manipulation  

    function bfm_curl_actions($list_id,$api_key,$post_data,$action) {

        $auth = base64_encode( 'user:'.$api_key );

        $data = array(
            'apikey'        => $api_key,
            'email_address' => $post_data['email'],
            'merge_fields'  => array(
            'FNAME' => $post_data['fname'],
            'LNAME' => $post_data['lname'],
            )
        );

        if($action == 'Subscribe' || $action == 'Add New Subscriber') :
            $data['status']='subscribed';
        elseif($action == 'Unsubscribe'):
            $data['status']='unsubscribed';
        endif;

        $member_id = md5($post_data['email']);

        $json_data = json_encode($data);

        $ch = curl_init();

        $curlopt_url = "https://us7.api.mailchimp.com/3.0/lists/$list_id/members/";
        if($action!='Add New Subscriber') $curlopt_url.=$member_id; // Member ID needs to be excluded if adding an entirely new person.
        curl_setopt($ch, CURLOPT_URL, $curlopt_url);
        if($action == 'Subscribe' || $action == 'Unsubscribe' || $action == 'Update') : 
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH");
        endif;
        if($action == 'Find'):
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        endif;
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
            'Authorization: Basic '.$auth));
        curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/3.0');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);

        $result = curl_exec($ch);
        $status = "undefined";
        $msg = "";
        $myArray = json_decode($result, true);

        foreach($myArray as $key => $value)
        {

            if( $key == "status" )
            {
                $status=$value;             
            }
            else if ($key == "title")
            {
                $msg=$value;                
            }       

        }

        $email = $post_data['email'];

        if($action == 'Subscribe' || $action == 'Add New Subscriber'): 
            if($status == "subscribed") :
                $report = array ('success'=>true,'error'=>'');
            else: 
                $report = array ('success'=>false,'error'=>array('email'=>$email,'message'=>$msg));
            endif;          
        endif;

        return $report;     

    }


    function bfm_subscriber_exists($email) {

        $api_key = bfm_api_key();
        $list_id = bfm_list_id();

        $auth = base64_encode( 'user:'.$api_key );

        $data = array(
            'apikey'        => $api_key,
            'email_address' => $email,
        );

        $member_id = md5($email);

        $json_data = json_encode($data);

        $ch = curl_init();

        $curlopt_url = "https://us7.api.mailchimp.com/3.0/lists/$list_id/members/$member_id";

        curl_setopt($ch, CURLOPT_URL, $curlopt_url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
            'Authorization: Basic '.$auth));
        curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/3.0');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);

        $result = json_decode(curl_exec($ch),true);

        if ($result['status']=='404') return false;

        return true;

        die(' '); // Free up memory.

    }
    ?>

以上所有作品。这是我尝试使用的 jQuery 来做同样的事情,但是通过 AJAX,它失败了。

// MailChimp Functions

$(document).on("submit","#mailchimp_actions", 
    function(event) {
        event.preventDefault();
        var import_data = $('#action').val();
        var action = $('#import_data').val();

        $.post("/ajax-curl-actions/",
            {   
                import_data: import_data,
                action: action
            },
            function () {
                alert("All done!");
            }
        );  
    }
);

解决了!我在 AJAX 请求中调换了两个变量:

 var import_data = $('#action').val();
 var action = $('#import_data').val();

应该是:

 var import_data = $('#import_data').val();
 var action = $('#action').val();