2016-08-23 3 views
2

Я надеюсь, что это простая проблема. Я использую API Mailchimp для отправки простой формы регистрации электронной почты с моего сайта. Я пытаюсь изучить javascript прямо сейчас, поэтому я пытаюсь выполнить httprequest и callback без jQuery. В основном, я пытаюсь преобразовать этот образец jQuery, который я нашел онлайн, в ванильный Javascript. Но что-то (несколько вещей?) Неправильно с моим javascript, который я не понимаю.Отправка электронной почты через ошибку возврата Mailchimp, Javascript и php

EDIT: Когда форма отправлена, я перейду на страницу 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 (это на самом деле бросает Аякса (...). Успех не является функцией ошибки в консоли, но по-прежнему представляет форму, 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 для проверки и отправки формы, как видно по ссылке выше. Html и php работают, чтобы отправить форму при использовании сценария jQuery, но не мой javascript, что означает, что в моем скрипте что-то не так, но я слишком новичок в javascript, чтобы полностью понять, что я пытаюсь сделать, и что я делаю неправильно.

Спасибо!

EDIT 2:

РНР код (копируется непосредственно из 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": "Ресурс не могут быть проверены. Подробные сведения о конкретном поле см. в массиве «errors»."," instance ":" "," errors ": [{" field ":" "," message ":" Обязательные поля не были указаны: email_address "}, {" field ":" email_address "," message ": «Схема описывает строку, найденную 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

В вашем PHP-скрипте должна возникать проблема, когда он вызывает API MailChimp. – Barmar

0

Вы можете добавить параметры URL вручную в URL:

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

И только тогда делать

request.send(); 

без данных в нем.

+0

Это не совсем то, как работает POST. – Paul

+0

Пробовал несколько разных способов, но он не работает. – ncox85