EmailJs is not sending email by React - javascript

I hope you are doing great, I am using Emailjs in React to get Emails. I configure Emailjs and it is properly sending test Emails but when I am trying to send from my project so it's not sending and even it is also not showing any error
Here is the template of the Email
Here is the ID and token which I hide but I am just showing this image to explain
clearly
(1) Here i import emailjs
import emailjs from '#emailjs/browser';
(2) Here is the function that will send the email, (Here in the fourth parameter I am just showing 5 characters as I hide in the above image )
function sendEmail(e) {
e.preventDefault();
emailjs.send('gmail', 'zaryabkhan864', e.target, 'G5CpT9*******')
.then((result) => {
console.log(result.text);
}, (error) => {
console.log(error.text);
});
e.target.reset()
}
(3) Here is the Form code
<form onSubmit={sendEmail}>
<div className="mb-3">
<label htmlFor="name" className="form-label">Your Name</label>
<input type="text" className="form-control" id="name" placeholder="Muhammad Zaryab Khan" name="name" />
</div>
<div className="mb-3">
<label htmlFor="email" className="form-label">Email address</label>
<input type="email" className="form-control" id="exampleFormControlInput1" placeholder="name#example.com" name="email" />
</div>
<div className="mb-3">
<label htmlFor="exampleFormControlTextarea1" className="form-label">Your Message</label>
<textarea className="form-control" id="Message" rows="5" name="message"></textarea>
</div>
<button type="submit" className="btn-theme">Send Message <i className="fa fa-paper-plane ms-2"></i></button>
</form>
Now I am receiving this error

add ref atribute for form, and ad useRef
const form = useRef<HTMLFormElement>(null);
after you should change e.target => form.current

const form = useRef();
const sendEmail = (e) => {
e.preventDefault();
emailjs.sendForm('service_id', 'template_id', form.current, 'user_id')
.then((result) => {
console.log(result.text);
}, (error) => {
console.log(error.text);
});
alert("Email Send");
};

Related

Issue posting data to api in react js

I am trying to send data to my contact form api through react but I am getting this problem
I tried to get input as a value to post through api when clicked on submit button but it is not working
error = the api should call like this https://edu.orgiance.com/api/contactus?secret=xxxxx-ac40-46a0-9c81-d48a1322f4bb&fname=test&email=test#test.com&mobile=8463274946&message=test
but it is calling like this
http://localhost:3000/?name=dfdfsd&email=dsffdsf%40gmail.com&phone=937285294&website=sxascsac&message=dscdscsfgcd#
My Code
import React from 'react';
const ContactForm = (props) => {
const { submitBtnClass } = props;
function handleClick() {
// Send data to the backend via POST
fetch('https://edu.orgiance.com/api/contactus?secret=f1794e34-ac40-46a0-9c81-d48a1322f4bb&fname=test&email=test#test.com&mobile=8463274946&message=', { // Enter your IP address here
method: 'POST',
mode: 'cors',
body: JSON.stringify(jsonData) // body data type must match "Content-Type" header
})
}
var jsonData = {
"contact": [
{
"fname": props.fname,
"email": props.email,
"mobile": props.phone,
"message": props.message
}
]
}
return (
<form id="contact-form" action="#">
<div className="row">
<div className="col-md-6 mb-30">
<input className="from-control" type="text" id="name" name="name" placeholder="Name" value={props.fname} required />
</div>
<div className="col-md-6 mb-30">
<input className="from-control" type="text" id="email" name="email" placeholder="E-Mail" value={props.email} required />
</div>
<div className="col-md-6 mb-30">
<input className="from-control" type="text" id="phone" name="phone" placeholder="Phone Number" value={props.phone} required />
</div>
<div className="col-md-6 mb-30">
<input className="from-control" type="text" id="website" name="website" placeholder="Your Website" required />
</div>
<div className="col-12 mb-30">
<textarea className="from-control" id="message" name="message" placeholder="Your message Here" value={props.message}></textarea>
</div>
</div>
<div className="btn-part" >
<button onClick={handleClick} className={submitBtnClass ? submitBtnClass : 'readon learn-more submit'} type="submit">Submit Now </button>
</div>
</form>
);
}
export default ContactForm;
It looks like you are creating a functional stateless component. That means your data needs to be passed in the props object, and if you are trying to access it anywhere in the ContactForm component, you would need to use this format: props.variablename . ie:
<input className="from-control" type="text" id="name" name="name" placeholder="Name" value={props.fname}required />
All of those variables are undefined. You can't initialize that jsonData object with variables that don't exist, you also can't set <input value={undefinedVariable} ... />
Since you are using form, an easy thing to do is to change it to look something like:
<form onSubmit={this.handleClick}>
...
<input type="submit" value="Submit" />
</form>
Then you can access the form data from the mouse event.
Example:
function handleClick(event) {
event.preventDefault();
const form = event.target;
const jsonData = {
"fname": form.name,
"email": form.email,
"mobile": form.phone,
"message": form.message
};
fetch('https://edu.orgiance.com/api/contactus?secret=f1794exxxxxx',
method: 'POST',
mode: 'cors',
body: JSON.stringify(jsonData)
})
}

How can validate and send react form data to fire base data base?

I try it but not working
import React from "react";
import "./App.css";
import { useForm } from "react-hook-form";
import classNames from "classnames";
import { useState } from "react";
function App() {
const { register, handleSubmit,formState: { errors } } = useForm();
// console.log(errors);
const onSubmit = data => console.log(JSON.stringify(data));
const postData = async (e)=>{
e.preventDefault();
const res = await fetch("https://test1-5022f-default-rtdb.firebaseio.com/reactformData.json",
{
method:"POST",
header:{
"content-type":"application/json",
},
Here what I pass in body?
body:JSON.stringify(data)
}
)
};
There are many fields in my form but here I show some
return (
<div>
<div className="container">
<div className="form-group my-3 ">
<form name="Registration_form" id="Form" action="" method="POST" onSubmit={handleSubmit(onSubmit)}>
<div className="form-group my-3">
<label htmlFor="name">Name:</label>
<input
type="text"
name="Name"
id="Name"
className={classNames("form-control",{"is-invalid":errors.Name,})}
autoComplete="off"
{...register('Name',
{ required: true,
maxLength: 15,
pattern: /^[A-Za-z]+$/
})
}
/>
<span id="name" className="text-danger fw-bold">{errors.Name?.type === "required" && "This field is required"}</span>
<span id="name" className="text-danger fw-bold">{errors.Name?.type ==="maxLength" && "Length Should be less then 15"}</span>
<span id="name" className="text-danger fw-bold">{errors.Name?.type === "pattern" && "Digits are not allow"}</span>
</div>
</div>
<div className="form-group my-3">
<label htmlFor="email">Email: </label>
<input
type="text"
name="email"
id="email"
className={classNames("form-control",{"is-invalid":errors.email,})}
placeholder="email#example.com"
autoComplete="off"
{...register('email',
{
required: true,
pattern:/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/,
})
}
/>
<span id="mail" className="text-danger fw-bold">{errors.email?.type === "required" && "Email is required"}</span>
<span id="mail" className="text-danger fw-bold">{errors.email?.type === "pattern" &&"Invalid format"}</span>
</div>
<input type="submit" id="submit" value="submit" onClick={postData} className="btn btn-success my-3" />
</form>
That is code which I try but it not working anybody review it and give your valuable comments and suggestions
Basically I want form validation using react hook form,its done but when I stuck in passing data to fire base data base
when I use, useState then its override because react hook form already store it but how to pass it to data base with out useState??
Through react hook form
You should remove your onClick from the submit button and handle your form submission from the onSubmit event on the form. Send your form data to your firebase endpoint, from your onSubmit function like so.
<input type="submit" id="submit" value="submit" onClick={postData} <-- Remove this
className="btn btn-success my-3" />
...
const onSubmit = (data) => {
// All your form fields will the converted to json object (data)
// and will be handled by hooks form
console.log(data);
// send data to firebase API
const responseRaw = fetch(
"https://your-firebase-url",
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}
);
const response = responseRaw.json();
};

EmailJS not sending email, Service ID is invalid error

So I am trying to setup EmailJS for my project.. I am currently getting 'FAILED' logged when I submit, but I can not figure out why? Any help would be great thanks!
function sendMail(contactForm) {
emailjs.send("gmail", "rosie", {
"from_name": contactForm.name.value,
"from_email": contactForm.emailaddress.value,
"project_request": contactForm.projectsummary.value
})
.then(
function(response) {
console.log("SUCCESS", response);
},
function(error) {
console.log("FAILED", error);
}
);
return false; // To block from loading a new page
}
<form onsubmit="return sendMail(this);">
<input type="text" name="name" class="form-control" id="fullname" placeholder="Name" required/>
<input type="text" name="emailaddress" class="form-control" id="emailaddress" placeholder="Email" required/>
<textarea rows="5" name="projectsummary" class="form-control" id="projectsummary" placeholder="Project Description" required></textarea>
<button type="submit" class="btn btn-secondary center-block">Send Project Request</button>
</form>
The error text says that your service ID is incorrect. So you need to change your service ID and replace it with something in your dashboard.
The following link will help you:
https://www.emailjs.com/docs/rest-api/send/

AXIOS POST form submit to WordPress returning 200 with data returning 0

I have a contact form which I am trying to POST the data via AXIOS using formData to send email via WP_mail.
Submitting the form seems to be working in the sense of:
The page isn't refreshing/adding parameters to the url
Using for (var value of formData.values()) {console.log(value);} to check what values are being grabbed by formData, console.log shows the different input values
response.status is showing 200
The problems start with response.data returning 0 rather than the data from the form that is being submitted.
This is my form
<form class="js-process dark-form">
<fieldset>
<label for="name">First name*</label>
<input type="text" name="name" placeholder="Enter your first name" />
<label for="last-name">Last name*</label>
<input type="text" name="last-name" placeholder="Enter your last name" />
<label for="email-address">Email address*</label>
<input type="email" name="email-address" placeholder="Enter your email address" />
<label for="telephone">Telephone*</label>
<input type="tel" name="telephone" placeholder="Enter your phone number" />
</fieldset>
<fieldset>
<label for="enquiry-form">Nature of enquiry*</label>
<!-- TEMP -->
<select id="enquiry-form" name="enquiry-form" data-label-value="test">
<option disabled value="">test</option>
<option value="test">test</option>
<option value="test">test</option>
<option value="test">test</option>
</select>
<label for="your-message">Your message*</label>
<textarea name="your-message" placeholder="Please tell us your message"></textarea>
</fieldset>
<input type="submit" value="Submit">
</form>
This is my JS to POST the form data
import axios from 'axios';
const processForm = (e) => {
const form = e.target;
e.preventDefault();
// let formData = new FormData(form);
const formData = new FormData();
// Console.log all formData values for testing
for (var value of formData.values()) { console.log(value); }
formData.append('action', 'contact_form');
formData.append('first_name', 'my first name');
axios({
method: 'POST',
url: WP.ajax,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: formData,
})
.then(function (response) {
console.log(response);
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
},
(error) => {
console.log(error);
});
return false;
};
const initProcessForm = () => {
const forms = document.querySelectorAll('.js-process');
forms.forEach(form => {
form.addEventListener('submit', processForm);
});
};
export default initProcessForm;
I'm not sure what I am missing here to get the data from the form to POST correctly. I know i've not even got round to the WP_mail side of things! I am new to using AXIOS so if anyone can point me in the right direction with this code or has a better way of doing this i'd be grateful to know : )
Thanks in advance.

express validator how to get req.validationErrors() to front side?

Hello and thanks for reading. I try to use express-validator. It works fine and block the post if for instance the name input is empty. But I don't know how I can get the error message on the front side. I have tried lot of things without success. Hope somebody can help and sorry for the size of the message. Here is a link to the doc of express validator if it can help ( https://express-validator.github.io/docs/ )
My code...
I have create a basic form:
<form id="sign-in">
<div class="form-group">
<label for="nom">name</label>
<input id="name" type="text" class="form-control" placeholder="name" autocomplete="family-name">
</div>
<div class="form-group">
<label for="username">username</label>
<input id="username" type="text" class="form-control" placeholder="username" autocomplete="given-name">
</div>
<div class="form-group">
<label for="email">email</label>
<input id="email" class="form-control" type="email" placeholder="monemail#gmail.com" autocomplete="email"></input>
</div>
<div class="form-group">
<label for="password">password</label>
<input id="password" class="form-control" type="password" autocomplete="current-password"></input>
</div>
<div class="form-group">
<label for="confirm-password">confirm-password</label>
<input id="confirm-password" class="form-control" type="password" autocomplete="current-password"></input>
</div>
<button type="submit" class="btn btn-primary">sign-in</button>
</form>
</section>
<footer>
</footer>
<script type="module" src="/js/sign-in.js"></script>
Then I do my fetch on the file sign-in.js:
document.getElementById('sign-in').addEventListener('submit', event => {
event.preventDefault()
const name = document.getElementById('name').value
const username = document.getElementById('username').value
...
// Use fetch to post data into the DB
window.fetch(`${config.serverHost}/sign-in`, {
method: 'post',
body: JSON.stringify({
name,
username,
...
})
}).then((res, errors) => {
if (res.status === 200) {
window.parent.location.reload()
} else if (res.status === 422) {
DONT KNOW WHAT TO DO TO GET MY ERROR MESSAGE
}
})
})
And finaly the server side:
app.post('/sign-in', (req, res, next) => {
// Start express validator //
req.checkBody('name', 'Please write your name').notEmpty()
req.checkBody('username', 'Please write your name').notEmpty()
...
const errors = req.validationErrors()
if (errors) {
SEND ME BACK MY ERROR MESSAGE
} else {
this part works fine, thank you
}
})
You have two options here depending on how your client is setup:
Use either express-flash or connect-flash to send errors back to your view. See this for the differences.
Use res.json to send back the errors object you created from validationErrors(). Be sure to set the appropriate HTTP status as well.
As I found the solution I post it, it may be useful for others.
Here is the sign-in.js file:
.then(res => {
if (res.status !== 200) {
res.json()
.then(res => errorsMessages.innerHTML = res.map(e => `<p>${e.msg}</p>`).join(''))
} else {
window.parent.location.reload()
}
})
And the code for the server:
const errors = req.validationErrors()
if (errors) {
res.status(422).json(errors)
} else {...}
Thank you Francisco for your help.

Categories

Resources