How can AJAX be utilized to send form data to a server for validation before sending it to Cleverreach?

To send form data to a server for validation before sending it to Cleverreach using AJAX, you can create a PHP script that receives the form data, validates it, and then sends it to Cleverreach if it passes validation. You can use jQuery AJAX to send the form data to the PHP script asynchronously, allowing for real-time validation without reloading the page.

<?php
// Validate form data
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Perform validation here
    // If validation fails, return an error response
    // If validation passes, send data to Cleverreach
    // Example: send data to Cleverreach API
    $url = 'https://rest.cleverreach.com/v3/groups/1234/subscribe';
    $data = array(
        'email' => $_POST['email'],
        'attributes' => array(
            'firstname' => $_POST['firstname'],
            'lastname' => $_POST['lastname']
        )
    );
    $data_string = json_encode($data);
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Authorization: Bearer YOUR_API_KEY'
    ));
    
    $result = curl_exec($ch);
    curl_close($ch);
    
    // Handle Cleverreach API response
    if ($result) {
        echo json_encode(array('success' => true));
    } else {
        echo json_encode(array('error' => 'Failed to subscribe to Cleverreach'));
    }
}
?>