2016-08-23 55 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