Search code examples
phphtmlcontact-form

The redirection after submitting the form does not work


Hello and thank you in advance for your help.

I've created this contact form which, in theory, should redirect users to a page once they've clicked on "Submit". The PHP script sends me the form by email but the user remains on the form. Being a novice, I can't find the cause.

It's live here : https://scalemy.company/contact.html

PHP Script : (I've hidden the sensitive data)

<?php
// Use PHPMailer classes
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\OAuth;
use League\OAuth2\Client\Provider\Google;

date_default_timezone_set('Europe/Paris');

// Require PHPMailer autoload file
require '/home4/atypik/scalemy.company/vendor/phpmailer/phpmailer/src/PHPMailer.php';
require '/home4/atypik/scalemy.company/vendor/phpmailer/phpmailer/src/Exception.php';
require '/home4/atypik/scalemy.company/vendor/phpmailer/phpmailer/src/SMTP.php';
require '/home4/atypik/scalemy.company/vendor/autoload.php';

// Function to sanitize form inputs
function sanitize_input($input) {
    $input = trim($input);
    $input = stripslashes($input);
    $input = htmlspecialchars($input);
    return $input;
}

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Check if the hidden field is empty (anti-spam)
    if (!empty($_POST["honeypot"])) {
        header("Location: https://scalemy.company/success.html");
        exit;
    }

    // Initialize PHPMailer
    $mail = new PHPMailer(true);

    try {
        // Server settings for OAuth with Google
        $mail->isSMTP();
        $mail->Host = 'smtp.gmail.com'; // Google's SMTP server address
        $mail->SMTPAuth = true;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->AuthType = 'XOAUTH2';
        $mail->Port = 465; // TCP port to connect to

        // Google OAuth credentials
        $myemail = '[email protected]'; // Your Gmail email address
        $clientId = 'HIDDEN'; // Your OAuth client ID
        $clientSecret = 'HIDDEN'; // Your OAuth client secret
        $refreshToken = 'HIDDEN'; // Your OAuth refresh token

        // Configure OAuth
        $provider = new Google(
            [
                'clientId' => $clientId,
                'clientSecret' => $clientSecret,
            ]
        );
        $mail->setOAuth(
            new OAuth(
                [
                    'provider' => $provider,
                    'clientId' => $clientId,
                    'clientSecret' => $clientSecret,
                    'refreshToken' => $refreshToken,
                    'userName' => $myemail,
                ]
            )
        );

        // Form data
        $first_name = sanitize_input($_POST['first_name']);
        $last_name = sanitize_input($_POST['last_name']);
        $phone = sanitize_input($_POST['phone']);
        $email = sanitize_input($_POST['email']);
        $company_name = sanitize_input($_POST['company_name']);
        $role = sanitize_input($_POST['role']);
        $reasons = $_POST['reason'];
        $other_reason = sanitize_input($_POST['other_reason']);
        $description = sanitize_input($_POST['description']);
        $timeframe = sanitize_input($_POST['timeframe']);
        $contact_time = sanitize_input($_POST['contact_time']);

        // Check if $reasons is an array, otherwise convert it to one
        if (!is_array($reasons)) {
            $reasons = array($reasons);
        }

        // Combine selected reasons with custom reason if "Other" is selected
        if (in_array("Other", $reasons)) {
            // Add custom reason to reasons array
            $reasons[] = $other_reason;
        }

        // Implode reasons array into a comma-separated string
        $reasons_str = implode(", ", $reasons);


        // Recipient
        $mail->setFrom($email, $last_name);
        $mail->addAddress('[email protected]');

        // Email content
        $mail->isHTML(true);
        $mail->Subject = 'New Contact Form Submission';
        $mail->Body = "
            <h2>New Contact Form Submission</h2>
            <p><strong>First Name:</strong> $first_name</p>
            <p><strong>Last Name:</strong> $last_name</p>
            <p><strong>Phone:</strong> $phone</p>
            <p><strong>Email:</strong> $email</p>
            <p><strong>Company Name:</strong> $company_name</p>
            <p><strong>Role:</strong> $role</p>
            <p><strong>Reasons:</strong> $reasons_str</p>
            <p><strong>Other Reasons:</strong> $other_reason</p>
            <p><strong>Description:</strong> $description</p>
            <p><strong>Timeframe:</strong> $other_reason</p>
        ";

        // Send email
        $mail->send();
        header("Location: https://scalemy.company/success.html");
        exit;
    } catch (Exception $e) {
        // Log the error message to a file
        $error_message = "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
        file_put_contents('error_log', $error_message . PHP_EOL, FILE_APPEND);
    
        // Redirect to error page
        header("Location: error.php");
        exit;
    }
} else {
    header("Location: error.php");
    exit;
}
?>


Solution

  • Your HTML includes the assets/js/ajax-form.js , which has the following lines

        var form = $('#contact-form');
    
        var formMessages = $('.ajax-response');
    
        $(form).submit(function(e) {
            e.preventDefault();
    
    
            var formData = $(form).serialize();
    
            $.ajax({
                type: 'POST',
                url: $(form).attr('action'),
                data: formData
            })
            .done(function(response) {
                // Make sure that the formMessages div has the 'success' class.
                $(formMessages).removeClass('error');
                $(formMessages).addClass('success');
    
                // Set the message text.
                $(formMessages).text(response);
    
                // Clear the form.
                $('#contact-form input,#contact-form textarea').val('');
            })
    
    .... and other lines
    
    

    It means that when you click the submit button in the form (in this case for the form "contact-form"), it will NOT trigger a normal form submission (you have e.preventDefault()), but trigger the actions thru ajax

    Please note that in such case the "header" redirection in PHP will have no effect (already highlighted by comments above)

    Now if you want a form redirection AFTER the form is successfully submitted, then please put the redirection statement inside the .done block of ajax (say put the redirection line at the end of the block)

    So if you want to get redirected to https://scalemy.company/success.html, please use something like

    window.location.href="https://scalemy.company/success.html"; 
    

    So amend ajax-form.js and add the above line in the ajax .done block, make it like :

            $.ajax({
                type: 'POST',
                url: $(form).attr('action'),
                data: formData
            })
            .done(function(response) {
                // Make sure that the formMessages div has the 'success' class.
                $(formMessages).removeClass('error');
                $(formMessages).addClass('success');
    
                // Set the message text.
                $(formMessages).text(response);
    
                // Clear the form.
                $('#contact-form input,#contact-form textarea').val('');
     
    
    window.location.href="https://scalemy.company/success.html";
    
            })
    
    .... and other lines