In the code, the user composes an email by filling out an html form that takes in recipients, subject and body as inputs. I want to display an alert box if the the user didn't provide any recipients. But after clicking OK in the alert box, the inbox.js file re-loads and the user is presented with the "Inbox" mailbox. However, I want them to stay on the compose-mail view instead. I tried to run compose_email function after the alert box but it didn't work. How might I accomplish that?
inbox.js:
document.addEventListener('DOMContentLoaded', function() {
// Use buttons to toggle between views
document.querySelector('#inbox').addEventListener('click', () => load_mailbox('inbox'));
document.querySelector('#sent').addEventListener('click', () => load_mailbox('sent'));
document.querySelector('#archived').addEventListener('click', () => load_mailbox('archive'));
document.querySelector('#compose').addEventListener('click', compose_email);
// By default, load the inbox
load_mailbox('inbox');
});
function compose_email() {
// Show compose view and hide other views
document.querySelector('#display-email').style.display = 'none';
document.querySelector('#emails-view').style.display = 'none';
document.querySelector('#compose-view').style.display = 'block';
// Clear out composition fields
document.querySelector('#compose-recipients').value = '';
document.querySelector('#compose-subject').value = '';
document.querySelector('#compose-body').value = '';
// Send an Email
document.querySelector("#compose-form").onsubmit = function(){
const recipients = document.querySelector("#compose-recipients").value;
const subject = document.querySelector("#compose-subject").value;
const body = document.querySelector("#compose-body").value;
if(recipients.length === 0){
alert(`At least one recipient is required`);
compose_email();
}
else{
fetch('/emails', {
method: 'POST',
body: JSON.stringify({
recipients: recipients,
subject: subject,
body: body
})
})
.then(response => response.json())
.then(result => {
// Print result
console.log(result);
if(result[`error`]){
alert(`User does not exist`)
}
else{
load_mailbox("sent");
}
})
return false;
}
}
}
change your submit function to this and use preventDefault
document.querySelector("#compose-form").onsubmit = function(e){
e.preventDefault();
...
}
Related
I have the code below, completely new to programming and JavaScript. I need to merge the code, together, i.e. have 1 $(document).ready(function () please advise how to merge/organise code together in 1 file, so all logic carries out its jobs?
//Hide show the sub-cat field
$(document).ready(function () {
//Set field visibility for category
$("#test_category").change(SetFieldsVisibility);
$("#test_category").change();
});
function SetFieldsVisibility() {
var selectedValue = $("#test_category").val();
if (selectedValue === "") {
$("#test_subcategory").closest("tr").hide();
//$("#test_subcategory_name").attr("value","");
$("#test_subcategory_name").val("");
//$("#test_subcategory").attr("value","");
$("#test_subcategory").val("");
$("#test_subcategory_entityname").attr("value", "subcategory");
}
else {
$("#test_subcategory").closest("tr").show();
//$("#test_subcategory_name").attr("value","");
$("#test_subcategory_name").val("");
//$("#test_subcategory").attr("value","");
$("#test_subcategory").val("");
//$("#test_subcategory_entityname").attr("value","");
$("#test_subcategory_entityname").val("");
}
}
//MERGE BELOW CODE WITH TOP
$(document).ready(function () {
// register onPrimaryChange function to run on change of dwc_primarycategorization field
$("#test_category").change(onPrimaryChange);
$("#test_category").change();
$("#test_selectdepartment").change(selectdepartmentonChange);
$("#test_selectdepartment").change();
});
function selectdepartmentonChange() {
let primaryValue = $("#test_category option:selected").val();
let departmentValue = $("#test_selectdepartment option:selected").val();
if (departmentValue != null) {
primaryValue = departmentValue;
}
setSubCategory(primaryValue);
}
function onPrimaryChange() {
// get id of selected primary field
// this will work only if you render primary field as dropdown
let primaryValue = $("#test_category option:selected").val();
if (primaryValue == "281a04bf-84f4-eb11-94ef-000d3adae0c8" || primaryValue == "3ad4e7db-4533-ec11-b6e6-0022489a108f" || primaryValue == "7b7e1b08-62f4-eb11-94ef-000d3adae0c8") {
$("#test_selectdepartment").empty();
$("#test_selectdepartment").show();
$("#test_selectdepartment_label").show();
//get department category drop down
const query = "/fetchxml-subcategory-portal-lookup/?id=" + primaryValue;
fetch(query, {
method: "GET"
})
.then(response => response.json())
.then(data =>
Object(data.results)
.forEach(item => {
let option = document.createElement("option");
option.value = item.categoryid;
option.innerText = item.title;
$("#test_selectdepartment").append(option);
}))
.catch((error) => {
console.error('Error:', error);
});
// let the control load, then set....
setTimeout(function () {
let departmentValue = $("#test_selectdepartment option:selected").val();
if (departmentValue != null) primaryValue = departmentValue;
setSubCategory(primaryValue);
}, 500);
} else {
$("#test_selectdepartment").hide();
$("#test_selectdepartment_label").hide();
$("#test_selectdepartment").empty();
setSubCategory(primaryValue);
}
}
function setSubCategory(primaryValue) {
// remove all option from dependent field
$("#test_subcategory").empty();
const query = "/fetchxml-subcategory-portal-lookup/?id=" + primaryValue;
fetch(query, {
method: "GET"
})
.then(response => response.json())
.then(data =>
Object(data.results)
.forEach(item => {
let option = document.createElement("option");
option.value = item.categoryid;
option.innerText = item.title;
$("#test_subcategory").append(option);
}))
.catch((error) => {
console.error('Error:', error);
});
}
Sure. Just cut and paste your code from the second $(document).ready call into the first call.
$(document).ready(function () {
// First call:
// Set field visibility for category
$("#test_category").change(SetFieldsVisibility);
$("#test_category").change();
// Second call:
// register onPrimaryChange function to run on change of dwc_primarycategorization field
$("#test_category").change(onPrimaryChange);
$("#test_category").change();
$("#test_selectdepartment").change(selectdepartmentonChange);
$("#test_selectdepartment").change();
});
// the rest of your code stays down here
You can just put all the code into one function like this.
$(document).ready(function () {
//Hide show the sub-cat field
$("#test_category").change(SetFieldsVisibility); //Set field visibility for category
$("#test_category").change();
// register onPrimaryChange function to run on change of dwc_primarycategorization field
$("#test_category").change(onPrimaryChange);
$("#test_category").change();
$("#test_selectdepartment").change(selectdepartmentonChange);
$("#test_selectdepartment").change();
});
After submitting, I want to hide my form elemnt from page. I've tried using myForm.style.display == "none" but it doesn't work. Can someone assist me?
let myForm = document.getElementById('contact-form');
myForm.addEventListener('submit', (e) => {
e.preventDefault();
const formData = new FormData(myForm);
fetch('#/api/contact_form_messages', {
method: 'post',
body: formData
})
.then((checkStatus))
.then((response) => {
document.getElementById("success-msg").innerHTML = "Success";
myForm.style.display == "none";
return response.text();
})
You need to assign, not compare, this is incorrect:
myForm.style.display == "none"; // Incorrect
This is correct:
myForm.style.display = "none"; // Correct
I want to redirect to the homepage and flash a message using flask, and I think I need to disable the preventDefault() function:
login_form.addEventListener("submit", (event) => {
event.preventDefault();
axios.post(login_form.action, {
username: login_form.username.value,
password: login_form.pass.value
}).then((response) => {
if (response.data["returnval"] === "wrong-crd")
{
_alert.innerHTML = "Username or password is incorrect";
_alert.hidden = false;
}
else
{
window.location.href = "/";
}
});
});
The code works but I can't flash a message, how can I disable the preventDefault() function.
My flask code:
#app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "GET":
return render_template("login.html")
else:
username = request.json.get("username")
password = request.json.get("password")
cursor.execute("SELECT * FROM Users WHERE username = %s", (username,))
returned = cursor.fetchall()
if len(returned) == 0:
return jsonify(returnval="wrong-crd")
if check_password_hash(returned[0][3], password):
session.permanent = True
session["userId"] = returned[0][0]
flash("Logged in!")
return redirect("/")
else:
return jsonify(returnval="wrong-crd")
Since AJAX is asynchronous, it means that it takes time to get the response after you submit your request.
If you do not prevent default event on the start, it will usually trigger that default event BEFORE you even receive your response.
You can do something like this :
Make a function that will make a popup message, something like this :
function pushNotification(message){
alert(message);
}
We are going to be using localStorage to store popup messages that need to be shown.
So firstly we are going to add a small code to your main javascript file that will trigger the function that we just made :
let nextMSG = localStorage['nextMessage'];
if(nextMSG!=undefined && nextMSG!=""){
pushNotification(nextMSG);
localStorage['nextMessage']="";
}
Now all you have to do is modify your code so that :
a) - When the response fails(user doesn't log in), you call pushNotification() function directly
b) - When the user logs in, you firstly change value of localStorage['nextMessage'] to a value that you want the user to see after redirect, and then redirect the user to wanted location.
You could just call login_form.submit() to proceed with the default submission if the field values are correct.
login_form.addEventListener("submit", (event) => {
event.preventDefault();
axios.post(login_form.action, {
username: login_form.username.value,
password: login_form.pass.value
}).then((response) => {
if (response.data["returnval"] === "wrong-crd")
{
_alert.innerHTML = "Username or password is incorrect";
_alert.hidden = false;
}
else
{
login_form.submit();
}
});
});
I have .js file where I loop through Firebase real time database to find email and password of registered users which is stored under /users tree in database where each child is randomly generated unique id which has user information. I am getting email and password information from form element. Problem is the alert messages in checkMessage are not executed when email and password do not equal same. Alert message should be displayed but only page refreshes.
Database:
----/Users
--------/XJIGFDMDKGD
-------------email: "a#b.com"
-------------password: "12345"
--------/XJFGNRIENGJ
-------------email: "c#d.com"
-------------password: "67890"
My code:
document
.getElementById('loginForm')
.addEventListener('submit', formSubmit);
function formSubmit(e) {
e.preventDefault();
document.querySelector('.alert').style.display = 'block';
// Get Values from the DOM
let email = document.querySelector('#email').value;
let password = document.querySelector('#password').value;
//check message values
checkMessage(email, password);
//Form Reset After Submission
//document.getElementById('loginForm').reset();
}
checkMessage function:
function checkMessage(email, password) {
var usrs = firebase.database().ref('users');
usrs.on("child_added", function(snapshot) {
var user = snapshot.val();
if (user.email == email) {
if (user.password == password) {
} else {
}
} else {
document.querySelector('.alert2').style.display = 'block';
setTimeout(function() {
document.querySelector('.alert2').style.display = 'none';
}, 7000);
document.getElementById('loginForm').reset();
}
);
}
The error was caused by syntax problem, an extra brace at the end of the following section of code, as well as a misplaced parentheses. Fixed solution:
var users = firebase.database().ref('users');
users.on("child_added", function(snapshot) {
var user = snapshot.val();
if (email == user.email) {
if (password == user.password) {
}
} else {
};
});
I have created a validation in javascript which detect if there's an empty field and if there's none then it will now insert into database which I use a PHP code.
But it does nothing I'm having trouble inserting into database, I think because I put e.preventDefault(), I put the e.preventDefault() so it will not reload and show the validation messages that I created.
(function() {
document.querySelector('#addForm').onsubmit = function (e) {
e.preventDefault();
const name = document.querySelector('#name');
const age = document.querySelector('#age');
const email = document.querySelector('#email');
//Check empty input fields
if(!document.querySelector('#name').value){
name.classList.add('is-invalid');
}else{
name.classList.remove('is-invalid');
}
if(!document.querySelector('#age').value)
{
age.classList.add('is-invalid');
}else{
age.classList.remove('is-invalid');
}
if(!document.querySelector('#email').value){
email.classList.add('is-invalid');
}else{
email.classList.remove('is-invalid');
}
}
})();
You should only e.preventDefault() if any of the inputs are empty then, example updated:
document.querySelector('#addForm').onsubmit = function(e) {
const name = document.querySelector('#name');
const age = document.querySelector('#age');
const email = document.querySelector('#email');
let formIsInvalid = false;
//Check empty input fields
if (!name.value) {
name.classList.add('is-invalid');
formIsInvalid = true;
} else {
name.classList.remove('is-invalid');
}
if (!age.value) {
age.classList.add('is-invalid');
formIsInvalid = true;
} else {
age.classList.remove('is-invalid');
}
if (!email.value) {
email.classList.add('is-invalid');
formIsInvalid = true;
} else {
email.classList.remove('is-invalid');
}
if (formIsInvalid) {
e.preventDefault();
}
}
You should append AJAX request to send values to the server
var th = $(this);
$.ajax({
type: "POST",
url: "handler.php", //Change
data: th.serialize()
}).done(function() {
alert("Thank you!");
setTimeout(function() {
// Done Functions
th.trigger("reset");
}, 1000);
});