jQuery AJAX帖子只找到多行文本框的第一行

时间:2016-09-01 08:50:09

标签: php jquery ajax wordpress mailchimp

我在WordPress上有一个POST表单,我用它通过其API将数据传递给MailChimp。

本身(即不使用jQuery),它按预期工作。但是,当我尝试通过AJAX后期操作传递数据而不是使用表单操作导航到新页面时,它只会找到多行文本框的第一行。

FORM

<?php 

    // Template Name: MailChimp Form 
    get_header();

?>

<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>

<?php get_footer(); ?>

处理$ _POST数据的页面

<?php 

    // Template: AJAX - cURL actions.

    ###############################################################################
    #                                                                             # 
    #   Available options:                                                        #
    #                                                                             #     
    #   Add New Subscriber - Create a new subscriber and add them to a list.      #
    #   Subscribe - Add an existing email to the specified list.                  #
    #   Unsubscribe - Completely unsubscribe an email from all mailers.           #
    #   Update - Change subscriber information.                                   #
    #                                                                             #
    ###############################################################################

    $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;

?>

功能

// 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.

    }

这样,按预期工作。第二页将第一页的数据导入MailChimp。

但是,如果我尝试使用以下jQuery通过AJAX执行相同操作,它仍会导入MailChimp,但只包含多行文本框的第一行;所有其他行都被忽略。

$(document).on("submit","#mailchimp_actions", 
        function(event) {
            event.preventDefault();
            var bfm_action = $('#action').val();
            var bfm_import = encodeURIComponent($('#import_data').val());
            console.log(bfm_action);
            console.log(bfm_import);
            $.post("/ajax-curl-actions/",
                {   
                    import_data: bfm_import,
                    action: bfm_action,
                },
                function () {
                    alert("Successful import.");    
                }
            );  
        }
    );

我错过了什么?如何让它识别文本框中的所有行?

2 个答案:

答案 0 :(得分:2)

似乎问题是由双重转义变量引起的:当你将键值对作为对象发送时,一次由你,然后再由jQuery。

如果您将键值对发送到任何jQuery的ajax方法,jQuery会为您处理转义,以便您删除encodeURIComponent

$(document).on("submit","#mailchimp_actions", 
    function(event) {
        event.preventDefault();
        var bfm_action = $('#action').val();
        var bfm_import = $('#import_data').val();
                         ^^^^^^^^^^^^^^^^^^^^^^^ here
        console.log(bfm_action);
        console.log(bfm_import);
        ...

答案 1 :(得分:0)

请尝试更改此行代码

function bfm_data_format($data) {
  $import_data = nl2br(urldecode($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;
}