Submitting form to PHP file after javascript validation - Hack The Tech - Latest News related to Computer and Technology

Hack The Tech - Latest News related to Computer and Technology

Get Daily Latest News related to Computer and Technology and hack the world.

Monday, April 24, 2023

Submitting form to PHP file after javascript validation

For a contact form I have added basic validation, however when trying to submit the form to a PHP file in order to actually send an email - the form is refusing to submit I have no idea as to why and I have no idea how to fix it

I have made the button type="submit" as well as making the form action="contactform.php" none have heeded any results

Below I have added the contact form,javascript file in question as well as the PHP file I'm trying to send it to

Of course I cannot use my details for PHPMailer so you will need to add your own

Thanks

HTML - contact_us.php

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="shortcut icon" type="image/x-icon" href="../img/logo.png">
        <!-- Page Title -->
        <title>LNEM - Womens</title>
    
        <!-- CSS -->
        <link rel="stylesheet" href="../css/contact.css"/>
    
        <!-- Icon CSS -->
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons+Outlined" rel="stylesheet">
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    </head>
    <body>
        <div class="contact-form">
            <div class="first-container">
                <div class="info-container">
                    <div>
                        <h3>Postal Address</h3>
                        <p>Unit 82 <br> Shingshowers Road <br> Deeblock Steppers Estate <br> Broward County <br> BR19 0DW</p>
                    </div>
                    <div>
                        <h3>Contact Email</h3>
                        <p>support@lnem.co.uk</p>
                    </div>
                    <div>
                        <h3>Telephone</h3>
                        <p>+44 XXXX XXXXXX</p>
                    </div>
                </div>
            </div>
            <div class="second-container">
                <h2>CONTACT US</h2>
                
                <form id="contact_form" method="post" name="ContactForm" >
                    <div class="form-group">
                        <label for="name">Name</label>
                        <input id="contact_name" name="name" type="text" placeholder="John Doe">
                        <small></small>
                    </div>
                    <div class="form-group">
                        <label for="name">Email</label>
                        <input id="contact_email" name="email" type="text" placeholder="example@gmail.com">
                        <small></small>
                    </div>
                    <div class="form-group">
                        <label for="name">Subject</label>
                        <input id="contact_subject" name="subject" type="text" placeholder="Order">
                        <small></small>
                    </div>
                    <div class="form-group">
                        <label for="message">Message</label>
                        <textarea id="contact_message" name="message" type="text" placeholder="Message"></textarea>
                        <small></small>
                    </div>
                    <button type="submit" name="submit" class="btn" >Send Message</button>
                </form>
            </div>
        </div>

        <script src="../js/validation/contactval.js"></script>

    </body>

</html>

PHP File - contactform.php

<?php

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

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


if (isset($_POST['submit'])) {
    $name = $_POST['name'];
    $subject = $_POST['subject'];
    $mailFrom = $_POST['email'];
    $message = $_POST['message'];

    $mailTo = "";
    $headers = "From: ".$mailFrom;
    $txt = "You have recieved an e-mail from ".$name.".\n\n".$message;
    
    $mail = new PHPMailer(true);

    $mail-> isSMTP();
    $mail ->Host = 'smtp.gmail.com';
    $mail -> SMTPAuth = true;
    $mail ->Username = '';
    $mail ->Password = '';

    $mail ->setFrom($mailFrom);
    $mail ->addAddress($mailTo);
    $mail ->isHTML(true);
    $mail ->Subject = $subject;
    $mail ->Body = $txt;
    $mail ->send();

    header('Location: contact_us.php?success');
}
else{
    header('Location: contact_us.php');
}

?>

Javascript

const ContactName = document.querySelector('#contact_name');
const ContactEmail = document.querySelector('#contact_email');
const ContactSubject = document.querySelector('#contact_subject');
const ContactMessage = document.querySelector('#contact_message');

const ContactForm = document.querySelector('#contact_form');
const submitform  = document.getElementById('contact_form');


const checkContactName = () => {

    let valid = false;

    const min = 1,
        max = 50;

    const c_name = ContactName.value.trim();

    if (!isRequired(c_name)) {
        showError(ContactName, 'Name cannot be blank.');
    } else if (!isBetween(c_name.length, min, max)) {
        showError(ContactName, `Name must be between ${min} and ${max} characters.`)
    } else {
        showSuccess(ContactName);
        valid = true;
    }
    return valid;
};


const checkContactEmail = () => {
    let valid = false;
    const c_email = ContactEmail.value.trim();
    if (!isRequired(c_email)) {
        showError(ContactEmail, 'Email cannot be blank.');
    } else if (!isEmailValid(c_email)) {
        showError(ContactEmail, 'Email is not valid.')
    } else {
        showSuccess(ContactEmail);
        valid = true;
    }
    return valid;
};

const checkContactSubject = () => {

    let valid = false;

    const min = 2,
        max = 50;

    const c_subject = ContactSubject.value.trim();

    if (!isRequired(c_subject)) {
        showError(ContactSubject, 'Message cannot be blank.');
    } else if (!isBetween(c_subject.length, min, max)) {
        showError(ContactSubject, `Message must be between ${min} and ${max} characters.`)
    } else {
        showSuccess(ContactSubject);
        valid = true;
    }
    return valid;
};


const checkContactMessage = () => {

    let valid = false;

    const min = 2,
        max = 500;

    const c_message = ContactMessage.value.trim();

    if (!isRequired(c_message)) {
        showError(ContactMessage, 'Message cannot be blank.');
    } else if (!isBetween(c_message.length, min, max)) {
        showError(ContactMessage, `Message must be between ${min} and ${max} characters.`)
    } else {
        showSuccess(ContactMessage);
        valid = true;
    }
    return valid;
};


const isEmailValid = (c_email) => {
    const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(c_email);
};



const isRequired = value => value === '' ? false : true;
const isBetween = (length, min, max) => length < min || length > max ? false : true;


const showError = (input, message) => {
    // get the form-field element
    const formField = input.parentElement;

    // show the error message
    const error = formField.querySelector('small');
    error.textContent = message;
};

const showSuccess = (input) => {
    // get the form-field element
    const formField = input.parentElement;

    // hide the error message
    const error = formField.querySelector('small');
    error.textContent = '';
}

function validateForm(){
    ContactForm.addEventListener('submit', function (e) {
        // prevent the form from submitting
        e.preventDefault();
    
        // validate fields
        let isNameValid = checkContactName(),
            isEmailValid = checkContactEmail();
            isSubjectValid = checkContactSubject();
            isMessageValid = checkContactMessage();
    
        let isFormValid = isNameValid &&
            isEmailValid && isSubjectValid &&
            isMessageValid;
    
        // submit to the server if the form is valid --> this is where I think code needs to be added
        if (isFormValid) {
        }
    });
}



const c_debounce = (fn, delay = 500) => {
    let timeoutId;
    return (...args) => {
        // cancel the previous timer
        if (timeoutId) {
            clearTimeout(timeoutId);
        }
        // setup a new timer
        timeoutId = setTimeout(() => {
            fn.apply(null, args)
        }, delay);
    };
};

ContactForm.addEventListener('input', c_debounce(function (e) {
    switch (e.target.id) {
        case 'contact_name':
            checkContactName();
            break;
        case 'contact_email':
            checkContactEmail();
            break;
        case 'contact_subject':
            checkContactSubject();
            break;
        case 'contact_message':
            checkContactMessage();
            break;
    }
}));





source https://stackoverflow.com/questions/76086456/submitting-form-to-php-file-after-javascript-validation

No comments:

Post a Comment