-2

I am trying to create a contact form which 1) sends a formatted message to the recipient e-mail, and 2) shows a success/error pop up message on the same page after the user submits the form.

I've tried to use JQuery AJAX form validation, but that causes my website to behave awkwardly (it already runs on Bootstrap CDN). This is why I use vanilla JavaScript for the AJAX request.

Currently, when I want to visit the contactform.html page, I immediately get a white screen with just an object with the default PHP message and status. What causes this?

AJAX request

const contactForm = document.addEventListener('DOMContentLoaded', function() {
            document.getElementById('contact-form').submit(function(e) {
                e.preventDefault();

                const xhr = new XMLHttpRequest();
                const url = 'contactform3.php';
                xhr.open('POST', url, true);
                xhr.setRequestHeader('Content-type', 'application/json');
                xhr.onreadystatechange = function() {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        let jsonData = JSON.parse(xhr.response);
                        console.log(jsonData);
                        document.getElementById('contact-form').reset();
                        document.querySelector('.response').innerHTML = 'Bedankt voor uw bericht. Wij nemen zo snel mogelijk contact met u op.';
                    } else {
                        document.querySelector('.response').innerHTML = 'Er is iets misgegaan.';
                    }
                };
            })
        })

PHP

<?php
    // Recipient Email
    $toEmail = 'info@example.com';

    $status = 0;
    $statusMsg = 'Er is iets misgegaan.';

    if(isset($_POST['contact_submit'])){

        // Get the submitted data
        $assignmentchoice = $_POST['assignmentchoice'];
        $projectchoice = $_POST['projectchoice'];
        $name = $_POST['name'];
        $lastname = $_POST['lastname'];
        $email = $_POST['email'];
        $tel = $_POST['tel'];
        $address = $_POST['address'];
        $zip = $_POST['zip'];
        $message = $_POST['message'];

        if(!empty($assignmentchoice) && !empty($projectchoice) && !empty($name) && !empty($lastname) && !empty($email) && !empty($message)) {
            if(filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
                $statusMsg = 'Vul een geldig e-mail adres in.';
            } else {
                $emailSubject = 'U heeft een nieuw bericht van'.$name;
                $htmlContent = '<h2>Je hebt een nieuw bericht</h2>
                    <h4>Opdracht:</h4><p>'.$assignmentchoice.'</p>
                    <h4>Project:</h4><p>'.$projectchoice.'</p>
                    <h4>Naam:</h4><p>'.$name.'</p>
                    <h4>Achternaam:</h4><p>'.$lastname.'</p>
                    <h4>Email adres:</h4><p>'.$email.'</p>
                    <h4>Telefoonnummer:</h4><p>'.$tel.'</p>
                    <h4>Adres locatie:</h4><p>'.$address.'</p>
                    <h4>Postcode locatie:</h4><p>'.$zip.'</p>
                    <h4>Bericht:</h4><p>'.$message.'</p>';

                $headers = "MIME-Version: 1.0" . "\r\n";
                $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
                $headers .= 'From: '.$name.'<'.$email.'>'. "\r\n";

                $sendEmail = mail($toEmail, $emailSubject, $htmlContent, $headers);
                if($sendEmail) {
                    $status = 1;
                    $statusMsg = 'Bedankt voor uw bericht. Wij nemen zo snel mogelijk contact met u op.';
                } else {
                    $statusMsg = 'Er is iets misgegaan.';
                }
            }
        } else {
            $statusMsg = 'Vul alstublieft alle velden in.';
        }
    }

    $response = array(
        'status' => $status,
        'message' => $statusMsg
    );
    echo json_encode($response);
?>

2 Answers2

1

"Currently, when I want to visit the contactform.html page, I immediately get a white screen with just an object with the default PHP message and status." - your js code is submitting the form straight away, instead of "listening" for the submit event. Change this line

document.getElementById('contact-form').submit(function(e) { ....

to

document.addEventListener("submit", function(e){ ....
Angel Deykov
  • 1,199
  • 1
  • 9
  • 15
1

Did you check your console for errors? The symptom you're decribing, where the JSON data shows up directly in the browser, indicates that the form posted back normally instead of using AJAX. This in turn indicates that your Javascript did not run properly.

Try changing

document.getElementById('contact-form').submit(function(e) { 

to

document.getElementById('contact-form').addEventListener("submit", function(e) {

The submit function is a jQuery-only thing.

The MDN documentation shows how you can use the "submit" event in native JS: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event


After that you need to amend the code further because as far as I can see you're not actually submitting the AJAX request with xhr.send(), nor are you pulling any of the data from the HTML form to populate it. See XMLHttpRequest to Post HTML Form and Send POST data using XMLHttpRequest for examples of what you need to do for that.

ADyson
  • 57,178
  • 14
  • 51
  • 63
  • I didn't see any errors in the console, that is why I didn't know in which direction to look. Thanks for your help, you're solution works! – Maurice Markslag Jul 16 '21 at 14:30
  • @MauriceMarkslag It's possible the errors were destroyed because the page immediately posted back. Click the "preserve log" box and then errors will not be cleared every time the page changes, this allows you to see problems in scenarios such as this. – ADyson Jul 16 '21 at 14:49