Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added backend api of contact form #258

Merged
merged 2 commits into from
Oct 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 43 additions & 20 deletions client/src/component/Footers/Contactus.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,22 @@ function ContactUs(props) {
const [isSubmitting, setIsSubmitting] = useState(false);
const [email, setEmail] = useState('');
const [name, setName] = useState('');
const [message, setMessage] = useState('');
const VITE_SERVER_PORT = import.meta.env.VITE_SERVER_PORT || 'https://bitbox-uxbo.onrender.com';

const handleSubmit = (e) => {

const handleSubmit = async (e) => {
e.preventDefault();
if (isSubmitting) return; // If already submitting, do nothing
setIsSubmitting(true); // Set isSubmitting to true to disable the button
if (isSubmitting) return; // Prevent multiple submissions
setIsSubmitting(true); // Disable the button

if(name==""){
// Validate name
if (!name.trim()) {
toast.error("Please enter a valid name");
setIsSubmitting(false);
return;
}

// Basic email validation regex
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(email)) {
Expand All @@ -27,25 +32,43 @@ function ContactUs(props) {
return;
}

const scriptURL = 'https://script.google.com/macros/s/AKfycby9s-kpS5yJrvU-igVgY4-B2m0YDoSVyhXHtpjmMAYjBQ2ECPBT7uZzy5qya9IyYq4/exec';
const form = document.forms['submit-to-google-sheet'];
// Validate message
if (!message.trim()) {
toast.error("Please enter a valid message");
setIsSubmitting(false);
return;
}


fetch(scriptURL, { method: 'POST', body: new FormData(form) })
.then(response => {
form.reset();
setIsSubmitting(false); // Re-enable the button
// props.showAlert("Form Submitted Successfully", "success");
toast.success("Form Submitted Successfully");
console.log('Success!', response);
})
.catch(error => {
setIsSubmitting(false); // Re-enable the button
// props.showAlert("Form Submission Failed", "danger");
toast.error("Form Submission Failed");
console.error('Error!', error.message);
try {
const response = await fetch(`${VITE_SERVER_PORT}/api/contact/submitContactForm`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name, email, message }),
});

const result = await response.json();
// Check if the request was successful
if (response.ok) {
toast.success('Message Sent Successfully!');
setName('');
setEmail('');
setMessage('');
} else {
toast.error(result.message || 'Error in submission!');
}
} catch (error) {
// Handle network or other fetch-related errors
toast.error('Something went wrong. Please try again.');
} finally {
// Reset the submitting state regardless of the outcome
setIsSubmitting(false);
}
};


return (
<div className="container contactus-container">
<h2 className='text-center Heading-Page'>Contact Us</h2>
Expand All @@ -69,7 +92,7 @@ function ContactUs(props) {
</div>
<div className="mb-3">
<label htmlFor="Message" className="form-label">Message:</label>
<textarea id="Message" name="Message" className="form-control" rows="5" placeholder='Write your message...' required='true'></textarea>
<textarea id="Message" name="Message" className="form-control" rows="5" placeholder='Write your message...' required='true' value={message} onChange={(e) => setMessage(e.target.value)}></textarea>
</div>
<button className="btn btn-light " type="submit" style={{ background: props.mode === 'dark' ? 'black' : 'white', color: props.mode === 'dark' ? 'white' : 'black', outline: props.mode === 'dark' ? '2px solid white' : '2px solid black' }}>
Submit
Expand Down
49 changes: 49 additions & 0 deletions server/Controllers/contact.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
const ContactForm = require('../Models/Contact');

const submitQueery = async (req, res) => {
console.log(req.body);

// Extract data from the request body
const { name, email, message } = req.body;

// Validate the presence of required fields
if (!name || !email || !message) {
return res.status(400).json({ error: "All fields are required: name, email, message." });
}

const contactData = {
name: name,
email: email,
msg: message,
createdAt: new Date(),
};

console.log(contactData);

try {
// Declare the variable properly
const queery = new ContactForm(contactData);

// Save to the database
await queery.save();

// Send a success response
res.status(200).json({ message: 'Contact form submitted successfully.' });
} catch (error) {
// Log the error for debugging
console.error("Error in submitting contact form:", error);

// Send an error response
res.status(500).json({ error: "Contact form not submitted successfully." });
}
}

const sayHello = async (req, res) => {
console.log("GET request to contact form route");
res.status(200).json({ message: 'Hello from the server!' });
}

module.exports = {
submitQueery,
sayHello
};
31 changes: 31 additions & 0 deletions server/Models/Contact.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const mongoose = require('mongoose');

// Define the schema for the contact form
const contactFormSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
trim: true,
lowercase: true,
match: [/.+\@.+\..+/, 'Please enter a valid email address']
},
msg: {
type: String,
required: true,
trim: true
},
createdAt: {
type: Date,
default: Date.now
}
});

// Create the model from the schema
const ContactForm = mongoose.model('ContactForm', contactFormSchema);

module.exports = ContactForm;
3 changes: 2 additions & 1 deletion server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,13 @@ app.use(

// Middleware to parse JSON requests
app.use(express.json());
app.use(helmet());
app.use(helmet());

// Available routes
app.use("/api/auth", require("./routes/auth"));
app.use("/api/projects", require("./routes/projects"));
app.use("/api/profile", require("./routes/profile"));
app.use("/api/contact", require("./routes/contact"));

// Socket.io connection handling
const users = {};
Expand Down
9 changes: 9 additions & 0 deletions server/routes/contact.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const express = require("express");
const router = express.Router();
const { submitQueery, sayHello } = require("../Controllers/contact");

router.post("/submitContactForm", submitQueery);
router.get("/contactHello", sayHello)


module.exports = router;
Loading