dongsuikai8286 2017-09-04 20:10 采纳率: 100%
浏览 65
已采纳

使用AJAX的Mailchimp API调用

I am using

error:function(exception){alert('Exception:'+ JSON.stringify(exception));}

to display an exception if there is an AJAX error, and here is the response i get:

Exception:{"readyState":4,"responseText":"","status":200,"statusText":"OK"}

This looks like a successful response to me, but it is the function that is called on error which means something is going wrong.

Here is the page: http://cuttingedgeconversions.com/free-month.html

I have a successful API call to subscribe a new email address to mail chimp using form action. But I do not want to redirect to another page after form submission, so I took out the 'form action' property and I tried adding this API call to script.js which uses ajax.

Here is the HTML:

<form class="email_form_freemonth" method="post">
<h3>Get your first month free</h3>
<div class="form-group customised-formgroup"> <span class="icon-user"></span>
<input type="text" name="full_name" class="form-control" placeholder="Name">
</div>
<div class="form-group customised-formgroup"> <span class="icon-envelope"></span>
<input type="email" name="email" class="form-control" placeholder="Email">
</div>
<!--<div class="form-group customised-formgroup"> <span class="icon-telephone"></span>
<input type="text" name="phone" class="form-control" placeholder="Phone (optional)">
</div>-->
<div class="form-group customised-formgroup"> <span class="icon-laptop"></span>
<input type="text" name="website" class="form-control" placeholder="Website (optional)">
</div>
<!--<div class="form-group customised-formgroup"> <span class="icon-bubble"></span>
<textarea name="message" class="form-control" placeholder="Message"></textarea>
</div>-->
<div>
<br>
<button style="margin: 0 auto" name="submit" type="submit" class="btn btn-fill full-width">GET FREE MONTH<span class="icon-chevron-right"></span></button>
</div>
</form>

Here is freemonth_action.php (which gets called in script.js, seen below):

<?php

session_start();
if($_SERVER['REQUEST_METHOD'] == "POST"){
    $name = trim($_POST['full_name']);
    $email = trim($_POST['email']);
    if(!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL) === false){
        // MailChimp API credentials
        $apiKey = '*****';
        $listID = '0cf013d1d9';

        // MailChimp API URL
        $memberID = md5(strtolower($email));
        $dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
        $url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listID . '/members/' . $memberID;

        // member information
        $json = json_encode([
            'email_address' => $email,
            'status'        => 'subscribed',
            'merge_fields'  => [
                'NAME'     => $name,
            ]
        ]);

        // send a HTTP POST request with curl
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        $result = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        //echo json_decode($result);

        // store the status message based on response code
        if ($httpCode == 200) {
            $_SESSION['msg'] = '<p style="color: #34A853">You have successfully subscribed to CodexWorld.</p>';
        } else {
            switch ($httpCode) {
                case 214:
                    $msg = 'You are already subscribed.';
                    break;
                default:
                    $msg = 'Some problem occurred, please try again.';
                    break;
            }
            $_SESSION['msg'] = '<p style="color: #EA4335">'.$msg.'</p>';
        }
    }else{
        $_SESSION['msg'] = '<p style="color: #EA4335">Please enter valid email address.</p>';
    }
}

I know these are correct because when I used 'form action = scripts/freemonth_action.php' it works. But I don't want the page to redirect on submission, so I have added an ajax call in my script that gets triggered from script.js. I have 2 ajax calls right now in script.js, the first one is working but the second one is not. The weird part is that BOTH RETURN STATUS CODE 200.

script.js with non-nested Ajax calls - WORKING PROPERLY NOW:

$('.email_form_freemonth').on('submit', function (e) {
        e.preventDefault();
        var _self = $(this);
        var __selector = _self.closest('input,textarea');
        _self.closest('div').find('input,textarea').removeAttr('style');
        _self.find('.msg').remove();
        _self.closest('div').find('button[type="submit"]').attr('disabled', 'disabled');
        var data = $(this).serialize();
        $.ajax({
            url: 'scripts/email_freeMonth.php',
            type: "post",
            dataType: 'json',
            data: data,
            success: function (data) {
                _self.closest('div').find('button[type="submit"]').removeAttr('disabled');
                if (data.code == false) {
                    _self.closest('div').find('[name="' + data.field + '"]').css('border-bottom', 'solid 2px red');
                    _self.find('.customised-formgroup').last().after('<div class="msg"><p style="color:red;padding:0;font-size:13px;font-weight:bold;position:absolute">*' + data.err + '</p></div>');
                } else {
                    $('.msg').html('<p style="color:green;padding:0;font-size:13px;font-weight:bold;position:absolute">' + data.success + '</p>');
                    _self.find('.customised-formgroup').last().after('<div class="msg"><p style="color:green;padding:0;font-size:13px;font-weight:bold;position:absolute">' + data.success + '</p></div>');
                    _self.closest('div').find('input,textarea').val('');
                }
            }
        });
        $.ajax({
            url: 'scripts/freemonth_action.php',
            type: "post",
            dataType: 'json',
            data: data,
            success: function (data) {
                _self.closest('div').find('button[type="submit"]').removeAttr('disabled');
                if (data.code == false) {
                    console.log("DATA.CODE == FALSE");
                } else {
                    console.log("DATA.CODE == TRUE");
                }
            }, 
            error:function(exception){alert('Exception:'+ JSON.stringify(exception));}
        });

    });
  • 写回答

2条回答 默认 最新

  • dongliulu1122 2017-09-05 05:01
    关注

    When you're passing serialized data through the AJAX request, if(isset($_POST['submit'])) won't evaluate as true because the button isn't part of the data being sent through the request. You can use if($_SERVER['REQUEST_METHOD'] == "POST") instead to check if the request was submitted. Just update that in your PHP file and it should work!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂