Click here to Skip to main content
15,887,267 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello guys. I am a beginner at coding. I have very small knowledge of php . I have created a webpage containing a form. When the form is submitted a mail needs to be send via phpmailer to a specific mail , and when there are errors the form can not be submitted. The problem that I am facing is that when I click on submit the form and the page is refreshing and I am loosing my data. I know that it has to smth to do with JavaScript but I do not know how fix it.

PHP
<pre><?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/phpmailer/phpmailer/src/Exception.php';
require 'vendor/phpmailer/phpmailer/src/PHPMailer.php';
require 'vendor/phpmailer/phpmailer/src/SMTP.php';

// Initialize the errors array
$errors = array();

if (isset($_POST["submit"])) {
    // Validate 'name' field
    if (empty($_POST["name"])) {
        $errors['name'] = 'Please enter name';
    }

    // Validate 'email' field
    if (empty($_POST["email"])) {
        $errors['email'] = 'Please enter email';
    } elseif (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
        $errors['email'] = 'Invalid email format';
    }

    // Validate 'phone' field
    if (empty($_POST["phone"])) {
        $errors['phone'] = 'Please enter phone number';
    }

    // Validate 'subject' field
    if (empty($_POST["subject"])) {
        $errors['subject'] = 'Please enter subject';
    }

    // Validate 'message' field
    if (empty($_POST["message"])) {
        $errors['message'] = 'Please enter message';
    }

    // If there are no validation errors, proceed with sending email
    if (empty($errors)) {
        try {
            $mail = new PHPMailer(true);

            $mail->isSMTP();
            $mail->Host = 'smtp-relay.brevo.com'; // Use Sendinblue's SMTP server
            $mail->SMTPAuth = true;
            $mail->CharSet = 'UTF-8';
            $mail->Username = 'pcelarnikdanevi@gmail.com'; // Replace with your Sendinblue username
            $mail->Password = 'dLFZwc4KHas6QRmU'; // Replace with your Sendinblue password
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Use STARTTLS
            $mail->Port = 587;

            $mail->addAddress('pcelarnikdanevi@gmail.com');
            $mail->setFrom($_POST['email']);
            $mail->addReplyTo($_POST['email']);

            $mail->isHTML(true);

            $mail->Subject = $_POST["subject"];
            $mail->Body = "This is the message from " . $_POST["message"];

            echo "Before sending email.<br>";

            $mail->send();

            echo "Email sent successfully!<br>";
        } catch (Exception $e) {
            echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}<br>";
        }
    } else {
        // Output a message if the form is not submitted
        echo "Form not submitted.<br>";
    }
}

?>



<pre>  <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
        <div class="b-form__inputWrap">
            <label for="name">Име</label>
            <input name="name" id="name">
            <?php
            if (isset($errors['name'])) {
                echo "<div class='error'>{$errors['name']}</div>";
            }
            ?>
        </div>

        <div class="b-form__inputWrap">
            <label for="email">Е-маил адреса</label>
            <input name="email" id="email">
            <?php
            if (isset($errors['email'])) {
                echo "<div class='error'>{$errors['email']}</div>";
            }
            ?>
        </div>

        <div class="b-form__inputWrap">
            <label for="phone">Телефонски број</label>
            <input name="phone" id="phone" placeholder="+389">
            <?php
            if (isset($errors['phone'])) {
                echo "<div class='error'>{$errors['phone']}</div>";
            }
            ?>
        </div>

        <div class="b-form__inputWrap">
            <label for="subject">Наслов</label>
            <input name="subject" id="subject">
            <?php
            if (isset($errors['subject'])) {
                echo "<div class='error'>{$errors['subject']}</div>";
            }
            ?>
        </div>

        <div class="b-form__inputWrap">
            <label for="message">Порака</label>
            <textarea name="message" id="message" placeholder="Внесета ја вашата порака"></textarea>
            <?php
            if (isset($errors['message'])) {
                echo "<div class='error'>{$errors['message']}</div>";
            }
            ?>
        </div>

        <button class="b-form__btn" type="submit" name="submit">Испрати</button>
    </form>


What I have tried:

I have tried this .
JavaScript
<pre>document.addEventListener('DOMContentLoaded', function () {
    var form = document.querySelector('form');

    form.addEventListener('submit', function (event) {
        event.preventDefault(); // Prevent the default form submission

        var formData = new FormData(form);

        fetch('./contact.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            // Check if the response indicates success
            if (data.success) {
                // If successful, update the content or redirect as needed
                console.log('Success:', data.message);
            } else {
                // If there are errors, display them
                console.error('Error:', data.message);

                // You can update your UI to show the errors if needed
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });
    });
});
But this producing an error and not sending an email <pre>contactUs.js:165 Error: SyntaxError: Unexpected token '<', "


<!DOCTYPE "... is not valid JSON
Posted

1 solution

Assuming you posted the contact.php code in your question, your fetch call to contact.php is expecting a json formatted response, not a HTML page, which is what your code is returning.

Google for "php json response" to find out how to do that. There's tons of examples.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900