Skip to main content
Contributor II
September 26, 2024
Solved

Noob question: How to send captured email from HTML to the list?

  • September 26, 2024
  • 5 replies
  • 139 views

I’ve made HTML form and it worked well V1, but it doesn’t work now with V2. It sends data to server and server sends the data to klaviyo… But since updates are made, I don’t know how to do the post request so it send the captured email to the list…. Can anyone help/explain?

    This topic has been closed for replies.
    Best answer by KeviSunshine

    Hi,

    You’re right, V2 is also disabled. I think they’re on “Revision” versions now, or something like that…

     

    I believe you’ll need to make the following 3 changes to make this work:

    1. Update your API URL to: https://a.klaviyo.com/api/lists/{list_id}/relationships/profiles/

    2. set your request body to:

    $data = array(
    'data' => array(
    array(
    'type' => 'profile',
    'email' => $email
    )
    )
    );

    3. set the following request headers:

    revision: 2024-07-15

    Authorization: Klaviyo-API-Key {privateKey}

     

    Cheers,

    Kevin.

    5 replies

    KeviSunshine
    Expert Problem Solver III
    Expert Problem Solver III
    September 26, 2024

    Hi @codxbre,

    Can you show how you were doing this with the V1 endpoint? If you share your V1 example, I can probably show you how to do this with the V2 endpoints.

     

    Remember to not share any sensitive data (like your API key!)

     

    Best,

    Kevin.

    codxbreAuthor
    Contributor II
    September 26, 2024

    Super simple:
     

    <form id="emailForm">
        <input type="email" id="emailInput" name="email" required placeholder="Your e-Mail">
        <span id="emailError" style="color: red; display: none;">Please enter a valid email address.</span>
        <button type="submit" class="smbtn" id="submitBtn">YES! SEND ME MY FREE BOOK</button>
    </form>


     

    <script>
        function waitForElement(selector, callback) {
            var interval = setInterval(function() {
                var element = document.querySelector(selector);
                if (element) {
                    clearInterval(interval);
                    callback(element);
                }
            }, 100); // Check every 100 milliseconds
        }

        waitForElement('#submitBtn', function(button) {
            button.addEventListener('click', function(event) {
                // Prevent form submission
                event.preventDefault();

                // Validate email format
                var emailInput = document.getElementById('emailInput');
                var emailError = document.getElementById('emailError');
                var isValidEmail = validateEmail(emailInput.value);

                if (!isValidEmail) {
                    emailError.style.display = 'block';
                    return;
                } else {
                    emailError.style.display = 'none';
                }

                // Show the processing message
                document.querySelector('.qsm-results-page').style.display = 'block';

                // Get the email address from the input field
                var email = emailInput.value;
                console.log('Email captured:', email); // Log the captured email
                
                // Get the list ID from somewhere in your JavaScript context (for example, from a variable)
                var listId = 'SDRTAf'; // Replace with your dynamic way of getting the list ID

                // Send the email address and list ID to your WordPress server via AJAX
                var xhr = new XMLHttpRequest();
                xhr.open('POST', 'https://improved-partner.com/wp-admin/admin-ajax.php');
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                xhr.onload = function() {
                    if (xhr.status === 200) {
                        //console.log('Email sent successfully.');
                        //alert('Email sent successfully.'); // Optionally, show an alert

                        // Redirect to Calendly upon successful email submission after 1 second delay
                        setTimeout(function() {
                            window.location.href = 'https://calendly.com/laurenconsulting/schedule';
                        }, 1000);
                    } else {
                        console.error('Failed to send email. Status code: ' + xhr.status);
                        //alert('Failed to send email. Please try again later.'); // Optionally, show an alert
                    }
                };
                xhr.onerror = function() {
                    console.error('Error sending email.');
                    //alert('Error sending email. Please try again later.'); // Optionally, show an alert
                };
                
                // Include the list ID in the data sent to PHP
                var data = 'action=send_email_to_klaviyo&email=' + encodeURIComponent(email) + '&list_id=' + encodeURIComponent(listId);
                //console.log('Sending data:', data); // Log the data being sent
                xhr.send(data);
            });
        });

        function validateEmail(email) {
            // Regular expression for basic email validation
            var re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            return re.test(email);
        }
    </script>


    ------------------------------------------

    PHP code (code snippets on WP):


     

    // Hook into WordPress AJAX actions
    add_action('wp_ajax_send_email_to_klaviyo', 'send_email_to_klaviyo');
    add_action('wp_ajax_nopriv_send_email_to_klaviyo', 'send_email_to_klaviyo'); // if you want to allow non-logged in users

    // AJAX handler function
    function send_email_to_klaviyo() {
        // Check if the email and list_id parameters are set
        if (isset($_POST['email'], $_POST['list_id'])) {
            // Sanitize and retrieve the email and list_id parameters
            $email = sanitize_email($_POST['email']);
            $list_id = sanitize_text_field($_POST['list_id']); // Assuming list_id is a string
            
            // Your Klaviyo private key
            $private_key = 'pk_1231231231231231232132177';

            // Prepare data to send to Klaviyo (adjust as per Klaviyo API docs)
            $data = array(
                'profiles' => array(
                    array(
                        'email' => $email
                    )
                )
            );

            // Initialize cURL session
            $curl = curl_init();

            // Set cURL options
            curl_setopt_array($curl, [
              CURLOPT_URL => "https://a.klaviyo.com/api/v2/list/{$list_id}/members?api_key={$private_key}",
              CURLOPT_RETURNTRANSFER => true,
              CURLOPT_ENCODING => "",
              CURLOPT_MAXREDIRS => 10,
              CURLOPT_TIMEOUT => 30,
              CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
              CURLOPT_CUSTOMREQUEST => "POST",
              CURLOPT_POSTFIELDS => json_encode($data),
              CURLOPT_HTTPHEADER => [
                "accept: application/json",
                "content-type: application/json"
              ],
            ]);

            // Execute cURL request
            $response = curl_exec($curl);
            $err = curl_error($curl);

            // Close cURL session
            curl_close($curl);

            // Check for cURL errors
            if ($err) {
                error_log('cURL Error #:' . $err);
                wp_send_json_error('Error sending data to Klaviyo: ' . $err);
            } else {
                // Log success response from Klaviyo
                error_log('Klaviyo API response: ' . $response);

                // Decode the JSON response
                $decoded_response = json_decode($response, true);

                // Check if Klaviyo returned a valid response
                if (isset($decoded_response['success']) && $decoded_response['success'] === true) {
                    wp_send_json_success('Email sent to Klaviyo.');
                } else {
                    wp_send_json_error('Failed to send email to Klaviyo.');
                }
            }
        } else {
            // If email or list_id parameter is not set, send an error response
            wp_send_json_error('Email or list_id parameter is missing.');
        }

        // Make sure to exit after sending the response
        wp_die();
    }
     

     

    codxbreAuthor
    Contributor II
    September 26, 2024

    Isn’t V2 disabled along with V1? Hmm

    KeviSunshine
    Expert Problem Solver III
    Expert Problem Solver III
    September 26, 2024

    Hi,

    You’re right, V2 is also disabled. I think they’re on “Revision” versions now, or something like that…

     

    I believe you’ll need to make the following 3 changes to make this work:

    1. Update your API URL to: https://a.klaviyo.com/api/lists/{list_id}/relationships/profiles/

    2. set your request body to:

    $data = array(
    'data' => array(
    array(
    'type' => 'profile',
    'email' => $email
    )
    )
    );

    3. set the following request headers:

    revision: 2024-07-15

    Authorization: Klaviyo-API-Key {privateKey}

     

    Cheers,

    Kevin.

    codxbreAuthor
    Contributor II
    September 27, 2024

    It worked wonders bro! Thanks, you’re a Godsent! Kudos