I have two(2) problem on my CONTACT FORM (practice)

Viewed 63

I have two(2) problem on my CONTACT FORM (practice).

"It is a working contact form try to move it on live"

1st: when I click on "Send message button", if the message is successfully sent the text next to the button must be color "blue" and the form must be "reset" - In my case even the message is successfully sent, the text that appear is color red and the form doesn't reset.

2nd: When I input an Invalid email address it generate a red Text stating "Invalid email address" next to the Send button (which is correct) , but when I change it to an Valid email address and click again the send button, the text that appear is just the last text and just changing it color to color blue. What I want is when I click the button again after an error message (In my case, the error message is "Invalid email address") the text that must appear is "Sending message..."

Here's the sample code.

<<index.html>>

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href=
"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.css">
</link>
    <link rel="stylesheet" href="./body.css">
    <link rel="icon" href="./icon/icon1.ico" type="image/x-icon">
    <title>Personal-CV</title>
</head>
<body>
    <section class="contact" id="contact">
        <h1 class="heading"><span>Contact </span>me</h1>
        <div class="row">
            <div class="content">
                <h3 class="title">Contact info</h3>
                    <div class="info">
                        <h3> <i class="fas fa-envelope"> </i>acct4568@gmail.com</h3>
                        <h3> <i class="fas fa-phone"> </i>+244-455-5555</h3>
                        <h3> <i class="fas fa-mobile"> </i>0987 654 3210</h3>
                        <h3> <i class="fas fa-map-marker-alt"> </i>Nara, Japan</h3>
                    </div>
            </div>
        <form action = "#">
           
            <input type="text" name="name" required placeholder="enter your name" class="box"> 
            <input type="text" name="email" required placeholder="enter your email" class="box">
            <input type="tel" pattern="[0-9]{4}-[0-9]{3}-[0-9]{4}" name="phone" required placeholder="ex. 1234-567-8900" class="box">
            <textarea cols="30" rows="10" class="box message" required placeholder="write your message" name="message"></textarea>
        <div class="button-area">
            <button type="submit">Send message<i class="fas fa-paper-plane"></i></button>
            <span >Sending your message...</span>
        </div>
        </form>
        </div>
    </section>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="./script.js"></script>
</body>
</html>

<<body.css>>

    @import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@100&display=swap');

:root {
    --gold:gold;
}

* {
    font-family: 'Montserrat', sans-serif;
    margin: 0; 
    padding: 0;
    box-sizing: border-box;
    outline: none;
    border: none;
    text-decoration: none;
    text-transform: capitalize;
    transition: all .2s linear;
}

*::selection{
    background:var(--gold);
    color: #201f1f;
}
html {
    font-size: 62.5%;
    overflow-x: hidden;
}

body{
    background: #201f1f;
    overflow-x: hidden;
  
}

section{
    min-height: 100vh;
    padding: 1rem;
}
.heading{
    text-align: center;
    margin: 0 6rem;
    font-size: 4rem;
    padding: 1rem;
    border-bottom: .2rem solid rgb(82, 78, 78);
    color: azure;
}
.heading span{
    color: rgb(221, 141, 123);
    font-weight: 900;
}

.contact .row{
    display: flex;
    padding-left: 10rem;
    align-items: center;
    justify-content: center;
    flex-wrap: wrap;
}
.contact .row .content{
    flex: 1 1 30rem;
    padding: 4rem;
    padding-bottom: 0;
}
.contact .row form{
    flex: 1 1 45rem;
    padding: 2rem;
    margin: 2rem;
    margin-bottom: 4rem;
}
.contact .row form .box{
    padding: 1.5rem;
    margin: 1rem 0;
    background: #625e5e85;
    color: rgb(205, 205, 205);
    text-transform: none;
    border-radius: 1rem;
    font-size: 1.7rem;
    font-weight: 700;
    width: 100%;
}

.button-area button{
    text-transform: none;
    padding: 1rem 2rem;
    background: #2d2d2d;
    color: azure;
    cursor: pointer;
    margin-top: 1rem;
    font-size: 2rem;
    font-weight: 800;
    border-radius: 5rem;
}
.button-area i{
    padding: 0 .5rem;
    font-size: 2rem;
}
.button-area button:hover{
    background: #4b5d67;
    color: #201f1f;
}
.button-area span{
    text-transform: none;
    margin: 1rem;
    font-size: 1.7rem;
    font-weight: 700;
    color: #1a66f1b1;
    display: none; 
}
.contact .row form .box::placeholder{
    font-weight: 800;
}
.contact .row form .message{
    height: 15rem;
    resize: none;
}
.contact .row .content .title{
    text-transform: uppercase;
    color: azure;
    font-size: 3rem;
    padding-bottom: 2rem;
}
.contact .row .content .info h3{
    display: flex;
    text-transform: none;
    color: azure;
    align-items: center;
    font-size: 2rem;
    padding: 1rem 0;
    font-weight: 600;
}
.contact .row .content .info h3 i{
    padding-right: 1rem;
    color: goldenrod;
}

<<script.js>>

    const form = document.querySelector("form"),
statusTxt = form.querySelector(".button-area span ");

form.onsubmit = (e) => {
   e.preventDefault();
   statusTxt.style.color = "#1a66f1b1";
   statusTxt.style.display = "inline-block";

   let xhr = new XMLHttpRequest();
   xhr.open("POST", "message.php", true);
   xhr.onload = () =>{
        if(xhr.readyState == 4 && xhr.status == 200){
            let response = xhr.response;
            if(response.indexOf("Invalid email address!") || response.indexOf("Failed to send your message"))
            {
            statusTxt.style.color = "#ff4c29";    
            }
            else{
                form.reset();
                setTimeout(() => {
                    statusTxt.style.display = "none";
                }, 3000);   
            }
            statusTxt.innerText = response;
        }
   }
   let formData = new FormData(form);
   xhr.send(formData);

}

<<message.php>>

    <?php
error_reporting(E_ERROR | E_PARSE);
    $name = $_POST['name'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $message = $_POST['message'];
    
    if(!empty($email) && !empty($message)){
        if(filter_var($email,FILTER_VALIDATE_EMAIL)){
        $receiver = "acct4568@gmail.com";
        $subject = "From: $name <$email>";
        $body = "Name: $name\nEmail: $email\nPhone: $phone\n\nMessage: $message";
        $sender = "From: $email";

            if(mail($receiver, $subject, $body, $sender)){
                echo"Your message has been sent";
            }
            else{
                echo"Failed to send your message";
            }
        }
        else{
            echo"Invalid email address!";
        }
    }
    
?>

I hope somebody can help me with this. Thank you.

1 Answers

The answer for your #1 is:
You are using indexOf() wrong in your JavaScript.

The indexOf() return -1 if not found otherwise it return 0 or more (depend on index number).

You have to check with if (response.indexOf('failed message') !== -1).
NOT with if (response.indexOf('failed message')).

The answer for your #2 is:
When the form event was submitted, the text sending in your HTML is gone and never come back from anywhere. So, you have to store this text in your JS file and set .innerText when form submit event fired but before AJAX request.

All your changed JS code is:

const form = document.querySelector("form"),
statusTxt = form.querySelector(".button-area span ");
const sendingMsgText = 'Sending your message...';

form.onsubmit = (e) => {
   e.preventDefault();
   statusTxt.style.color = "#1a66f1b1";
   statusTxt.style.display = "inline-block";
   statusTxt.innerText = sendingMsgText;// always show sending message on click submit button but before AJAX.

   let xhr = new XMLHttpRequest();
   xhr.open("POST", "message.php", true);
   xhr.onload = () =>{
        if(xhr.readyState == 4 && xhr.status == 200){
            let response = xhr.response;
            // check response `indexOf()` with not `-1` do not check with just `.indexOf()` because `-1` will be matched if no error returns.
            if(response.indexOf("Invalid email address!") !== -1 || response.indexOf("Failed to send your message") !== -1)
            {
                statusTxt.style.color = "#ff4c29";    
            }
            else{
                form.reset();
                setTimeout(() => {
                    statusTxt.style.display = "none";
                }, 3000);   
            }
            statusTxt.innerText = response;
        }
   }
   let formData = new FormData(form);
   xhr.send(formData);

}
Related