2016-08-23 71 views
2

我希望这是一个简单的问题。我使用Mailchimp API从我的网站提交简单的电子邮件注册表单。我正在尝试学习JavaScript,所以我正在尝试执行没有jQuery的httprequest和回调。基本上,我试图将我在网上找到的这个jQuery示例转换为vanilla Javascript。但有一些东西(几件事?)我的JavaScript错误,我不明白。通过Mailchimp邮件提交返回错误,Javascript和php

编辑:当表单被提交时,我被带到email-validate.php页面,并显示MailChimp返回的以下错误对象。

{"type":"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/","title":"Invalid Resource","status":400,"detail":"The resource submitted could not be validated. For field-specific details, see the 'errors' array.","instance":"","errors":[{"field":"","message":"Required fields were not provided: email_address"},{"field":"email_address","message":"Schema describes string, NULL found instead"}]} 

jQuery的

Found here(这实际上抛出一个AJAX(...)。成功不是在控制台的功能错误,但仍提交表单,FWIW)

$('document').ready(function(){ 
    $('.mc-form').submit(function(e){ 

    //prevent the form from submitting via the browser redirect 
    e.preventDefault(); 

    //grab attributes and values out of the form 
    var data = {email: $('#mc-email').val()}; 
    var endpoint = $(this).attr('action'); 

    //make the ajax request 
    $.ajax({ 
     method: 'POST', 
     dataType: "json", 
     url: endpoint, 
     data: data 
    }).success(function(data){ 
     if(data.id){ 
     //successful adds will have an id attribute on the object 
     alert('thanks for signing up'); 
     } else if (data.title == 'Member Exists') { 
     //MC wil send back an error object with "Member Exists" as the title 
     alert('thanks, but you are alredy signed up'); 
     } else { 
     //something went wrong with the API call 
     alert('oh no, there has been a problem'); 
     } 
    }).error(function(){ 
     //the AJAX function returned a non-200, probably a server problem 
     alert('oh no, there has been a problem'); 
    }); 
    }); 
}); 

我使用Javascript(不工作)

document.addEventListener("DOMContentLoaded", function() { 
    document.getElementById("mc-form", function submit(e){ 
     e.preventDefault(); 

     var data = {"email": document.getElementById("mc-email").value}; 
     var endpoint = document.getElementById("mc-form").getAttribute('action'); 

     function formSubmit(callback){ 
      var request = new XMLHttpRequest(); 

       request.onreadystatechange = function() { 
        if (request.readyState === 4) { 
         if (request.status === 200) { 
         //Parse returned string into an object, then pass the object to the callback function. 
         var response = JSON.parse(request.responseText); 
         callback(response); 
         } else { 
        console.log('JSON request error'); 
         } 
        } 
       } 
      request.open("POST", endpoint , true); 
      request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
      request.send(data); 
     } 
     function formResponse(response){ 
      if(response.id){ 
      //successful adds will have an id attribute on the object 
      alert('Thank you for signing up for Launch Alerts!'); 
      } else if (response.title == 'Member Exists') { 
      //MC wil send back an error object with "Member Exists" as the title 
      alert('You are already signed up for Launch Alerts!'); 
      } else { 
      //something went wrong with the API call 
      alert('Something went wrong. Please resubmit the form!'); 
      } 
     } 
     formSubmit(formResponse); 
    }) 
}); 

我的HTML

<form class="mc-form" method="POST" action="./email-validate.php"> 
    <h2 class="launch-alerts">Never miss a launch with Launch Alerts</h2> 
    <label for="mc-email">Email Address:</label> 
    <input type="email" id="mc-email" name="mc-email" autofocus="true" required/> 
    <input type="text" value="pending" id="status" name="status" hidden/> 
    <input type="submit" value="Submit"> 
</form> 

它使用php文件来验证并提交表单,可以在上面的链接中看到。在使用jQuery脚本时,html和php工作提交表单,但不是我的javascript,这意味着我的脚本有问题,但是我对JavaScript太新了,无法完全理解我正在尝试执行的操作,以及我做错了什么。

谢谢!

编辑2:

PHP代码(直接从here

<?php 
//fill in these values for with your own information 
$api_key = 'xxxxxxxxxxxxxxxxxxxxxxxx'; 
$datacenter = 'xxxxx'; 
$list_id = 'xxxxxxxxx'; 
$email = $_POST['email']; 
$status = 'pending'; 
if(!empty($_POST['status'])){ 
    $status = $_POST['status']; 
} 
$url = 'https://'.$datacenter.'.api.mailchimp.com/3.0/lists/'.$list_id.'/members/'; 
$username = 'apikey'; 
$password = $api_key; 
$data = array("email_address" => $email,"status" => $status); 
$data_string = json_encode($data); 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL,$url); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); 
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); 
curl_setopt($ch, CURLOPT_USERPWD, "$username:$api_key"); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json', 
    'Content-Length: ' . strlen($data_string)) 
); 
$result=curl_exec ($ch); 
curl_close ($ch); 
echo $result; 
?> 
+0

浏览器控制台中的错误是什么? – Danmoreng

+0

我没有收到控制台(还)的错误。请求正在发送,但mailchimp正在返回错误。 {“type”:“http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/”,“title”:“Invalid Resource”,“status”:400,“detail”:“资源提交的内容无法验证。有关特定于字段的详细信息,请参阅“错误”数组。“,”instance“:”“,”errors“:[{”field“:”“,”message“:”未提供必填字段:email_address“},{”field“:”email_address“,”message“ “Schema描述字符串,发现空值NULL”}]} – ncox85

回答

3

复制的数据参数request.send()必须是一个URL编码的字符串,要传递的对象jQuery不会这种转换。自动为你自己,当你自己做,你也必须自己做。

var data = "email=" + encodeURIComponent(document.getElementById("mc-email").value); 

你也没有添加您提交的乐趣正确地显示表格的submit事件。它应该是:

document.getElementById("mc-form").addEventListener("submit", function submit(e){ 
+0

好的,我试过了,它返回了同样的错误,这导致我相信我仍然在发送错误的信息。 – ncox85

+0

编辑我的问题以显示返回的错误来自Mailchimp – ncox85

+0

当你调用MailChimp API时,你的PHP脚本中必须存在另一个问题 – Barmar

0

您可以手动添加URL参数的URL:

var endpoint = document.getElementById("mc-form").getAttribute('action') + 
       "?email=" + document.getElementById("mc-email").value; 

然后只需

request.send(); 

没有它的数据。

+0

这不完全如何工作。 – Paul

+0

尝试了几种不同的方式,但它不起作用。 – ncox85