Sails.js - creating empty models - javascript

This is the controller that I am using to create a new instance of my human model:
newh: function(req, res) {
var firstName = req.param('firstName');
var lastName = req.param('lastName');
var contact = req.param('contact');
var email = req.param('email');
var home = 'http://localhost:1337/humans';
Human.create({
firstName: firstName,
lastName: lastName,
contact: contact,
email: email
}).done(function(err, user) {
if(err) {
return console.log('Could not create user. Error: ' + err);
}else{
res.redirect('/humans');
}
});
This is the script that I am using to post the data to the controller:
$(document).ready(function() {
var firstName = $('#first').val();
var lastName = $('#last').val();
var contact = $('#contact').val();
var email = $('#email').val();
$('#add').on('click', function() {
$.ajax({
type: 'POST',
url: '/humans/new',
data: {
firstName: firstName,
lastName: lastName,
contact: contact,
email: email
},
success: function() {
console.log('Successfully passed data.');
}
});
});
});
Whenever I post the information, the success function gets executed. Still, my controller doesn't seem to make use of that res.redirect() call and it simply generates empty instances of the human model.
What's the problem?
Thank you!

Related

how can I redirect to another html file after being able to store data in firestore?

I've first made my web store data on firebase real time database and
now I changed it to firestore but now I'm not quite sure how can I
redirect after data has been posted to firestore I tried adding location.href =
"https://dr-elvic-tengco-web.firebaseapp.com/ThankYou.html"; under
console.log("Document successfully written!");
yes it redirects and stores the data
and what I noticed it does work when I wait for 2 seconds before I
click the OK button on the window.alert("Appointment Request Sent!
Please wait for a confirmation on your Email or We'll txt you back!") but noone would wait for 2 seconds before you click "okay" button ,
right?
//I had this code first on firebase realtime database-this worked and redirected
var data = {
FirstName: firstName,
LastName: lastName,
Contact: cPhone,
Gender: inputGender,
Birthdate: Bday,
Address: inputAddress,
City: inputCity,
Province: inputState,
Zip: inputZip,
Email: exampleInputEmail1,
Message: inputMessage,
Clinic: inputClinic
};
var firebaseRef = firebase.database().ref();
firebaseRef.push(data, (error) => {
if (error) {
console.log('error');
} else {
location.href = "https://dr-elvic-tengco-web.firebaseapp.com/ThankYou.html";
}
})
//and now this is the firestore
<script>
//FOR REALTIME DABASE
function getInfo() {
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var cPhone = document.getElementById("cPhone").value;
var exampleInputEmail1 = document.getElementById("exampleInputEmail1").value;
var Bday = document.getElementById("Bday").value;
var inputGender = document.getElementById("inputGender").value;
var inputAddress = document.getElementById("inputAddress").value;
var inputCity = document.getElementById("inputCity").value;
var inputState = document.getElementById("inputState").value;
var inputZip = document.getElementById("inputZip").value;
var inputMessage = document.getElementById("inputMessage").value;
var inputClinic = document.getElementById("inputClinic").value;
if (!firstName || !lastName || !cPhone || !exampleInputEmail1 || !Bday || !inputGender || !inputAddress || !inputCity || !inputState || !inputZip || !inputMessage || !inputClinic) {
window.alert("Please Complete the Form! The Page will Reload For Security Purpose")
document.getElementById("gbutton").disabled = true;
document.location.reload()
} else {
window.alert("Appointment Request Sent! Please wait for a confirmation on your Email or We'll txt you back!")
var db = firebase.firestore();
db.collection("Requests").doc().set({
FirstName: firstName,
LastName: lastName,
Contact: cPhone,
Gender: inputGender,
Birthdate: Bday,
Address: inputAddress,
City: inputCity,
Province: inputState,
Zip: inputZip,
Email: exampleInputEmail1,
Message: inputMessage,
Clinic: inputClinic
})
.then(function() {
console.log("Document successfully written!");
location.href = "https://dr-elvic-tengco-web.firebaseapp.com/ThankYou.html";
})
.catch(function(error) {
console.error("Error writing document: ", error);
});
}
}
I have found an alternative by using setTimeout
.then(function() {
console.log("Document successfully written!");
setTimeout(function() {
location.href = "https://dr-elvic-tengco-web.firebaseapp.com/ThankYou.html";
}, 2000);
})
.catch(function(error) {
console.error("Error writing document: ", error);
});

How to fix nodemailer "object object" error in node.js website?

I am creating a node.js website for a business and would like to be able to notify through email, everytime someone applies. I am using nodemailer and mailgun to send an email every time the job application form is submitted. The emails are being sent, however, it does not contain the key value pairs of the applicant object I've created. Any help would be greatly appreciated!
Here is an image of the email I receive when submitting and application
Here is the nodemailer code I'm running
const nodemailer = require('nodemailer');
const mailgun = require('nodemailer-mailgun-transport');
const debug = require('debug')('app:mail');
const auth = {
auth: {
api_key: '**************',
domain: '***************'
}
};
const transporter = nodemailer.createTransport(mailgun(auth));
function sendOrderEmail(applicant) {
let html = '<ul>';
Object.entries(applicant).forEach(([key, value]) => {
html += `<li>${key}: ${value}</li>`;
});
html += '</ul>';
const mailOptions = {
from: '*************',
to: '*********, *************',
subject: '*****************',
html
};
transporter.sendMail(mailOptions, (err, info) => {
if (err) {
debug(`Error: ${err}`);
} else {
debug(`Info: ${info}`);
}
});
}
module.exports = sendOrderEmail;
Here is my post route where I create the applicant object
app.post('/employment', function(req, res){
var firstName = req.body.firstName;
var middleInitial = req.body.middleInitial;
var lastName = req.body.lastName;
var address = req.body.address;
var city = req.body.city;
var state = req.body.state;
var zipCode = req.body.zipCode;
var phoneNumber = req.body.phoneNumber;
var doYouRecieveText = req.body.doYouRecieveText;
var newApplicant = {
firstName: firstName,
middleInitial: middleInitial,
lastName: lastName,
address: address,
city: city,
state: state,
zipCode: zipCode,
phoneNumber: phoneNumber,
doYouRecieveText: doYouRecieveText
};
Applicant.create(newApplicant, function(err, newlyCreated){
if(err) {
console.log(err);
} else {
console.log(newlyCreated);
sendOrderEmail(newlyCreated);
res.redirect('/');
}
});
});
It looks like the value you are attempting to insert in your html is an Object but the html is expecting a value of type String.
Try stringifying your value before inserting it in your html.
html += `<li>${key}: ${ typeof value === 'string' ? value : JSON.stringify(value)}</li>`;
I was passing through the newlyCreated parameter to the sendOrderEmail function when I should have been passing through the newApplicant variable
Applicant.create(newApplicant, function(err, newlyCreated){
if(err) {
console.log(err);
} else {
console.log(newlyCreated);
sendOrderEmail(newApplicant);
res.redirect('/');
}
});

How do I access the user UID in my firebase database

I am working on a fantasy soccer web app based on a local league. So far, when a user is created using firebase auth, there is a respective node created in my firebase using the user uid as follows:
$scope.signUp = function (){
var username = $scope.user.email;
var password = $scope.user.password;
var teamname = $scope.user.teamname;
var fullname = $scope.user.fullname;
var ref = firebase.database().ref().child('users');
if(username && password){
var auth = $firebaseAuth();
auth.$createUserWithEmailAndPassword(username,
password).then(function(user){
console.log("User Successfully Created");
let usersRef = firebase.database().ref("users");
//child is created under users node with a user's user id as
child name
usersRef.child(user.uid).set({
email: user.email,
userName: username,
teamname: teamname,
fullname: fullname,
total: 0,
week:0
});
$location.path('/home');
}).catch(function(error){
$scope.errMsg = true;
$scope.errorMessage = error.message;
});
}
};
That part works fine. In the database, the JSON tree looks something like this:
users:{
user UID: {
email:
teamname:
fullname:
week:
}
}
I have a service I use for all my views :
.service('CommonProp',['$location','$firebaseAuth', function($location,$firebaseAuth){
var user = "";
var auth = $firebaseAuth();
return {
getUser:function(){
if(user == ""){
user = localStorage.getItem("userEmail");
}
return user;
},
setUser: function(value){
localStorage.setItem("userEmail", value);
user = value;
},
logoutUser: function(){
auth.$signOut();
console.log("Logged Out Successfully");
user = "";
localStorage.removeItem("userEmail");
$location.path('/home');
}
};
}]);
PROBLEM
My problem is that when I go to my 'select player' view, I do not know how to access the user UID so that I can set each user's selection for each week.This is what I tried to do :`
$scope.saveTeam = function(user){
$scope.history = [];
var uid = user.uid;
var ref2 = firebase.database().ref("users/" + auth.uid + "/week");
ref2.set($scope.history);
};
Is there a way that I can access each user's respective "week" child node under their respective user uid?

Meteor method call - wait for method to complete

I am really struggling with Meteor callbacks. I have a client side call to a server side method, but when the callback comes back from the server, I get an undefined result. As far as I can tell, this is because the server is not finished doing the POST but is already sending the callback. I am new to Meteor and this seems really difficult. What I have so far:
Client:
Meteor.call("createCustomer", city, fname, lname, email, function(error, result) {
if (error) {
console.log("error: " + error);
} else {
console.log("result: " + result)
}
});
Server:
Meteor.methods({
'createCustomer': function(city, fname, lname, email) {
HTTP.call("POST", url+'/customer?api_key='+process.env.API_TOKEN ,{
data: {
city: city,
first_name: fnam,
last_name: lname,
email: email
}
}, function (error, result) {
if (error) {
return 'error';
} else {
return'success';
}
});
}
});
I might be doing something really stupid, or it might be more complex than I had anticipated, but any help would go a long way!
This is what Meteor.wrapAsync is for. It creates a synchronous version of an asynchronous function. Try this:
'createCustomer': function(city, fname, lname, email) {
var call = Meteor.wrapAsync(HTTP.call, HTTP);
return call("POST", url+'/customer?api_key='+process.env.API_TOKEN ,{
data: {
city: city,
first_name: fname,
last_name: lname,
email: email
}
});
}
Expanding my original comment.
On the server if you don't pass callback, HTTP.call runs synchronously, and no need to use Meteor.wrapAsync.
Meteor.methods({
createCustomer(city, first_name, last_name, email) {
return HTTP.post(`${url}/customer?api_key=${process.env.API_TOKEN}`, {
data: { city, first_name, last_name, email }
});
}
});

Alloy MVC Framework Titanium Network (Model)

I'm trying to authenticate using the Model in Alloy. I have been trying to figure this problem out since yesterday. If anybody could help me, I'd really appreciate it.
So, I have a view login.xml, then a controller login.js. The login.js contains the following function:
var user = Alloy.Models.user; //my user.js model
function login(e) {
if($.username.value !== '' && $.password.value !== ''){
if(user.login($.username.value, $.password.value)){
Alloy.createController('home').getView().open();
$.login.close();
}
}else{
alert('Username and/or Password required!');
}
}
Then in my user.js model, it's like this:
extendModel : function(Model) {
_.extend(Model.prototype, {
login: function(username, password) {
var first_name, last_name, email;
var _this = this;
var url = 'http://myurl.com/test.php';
var auth = Ti.Network.createHTTPClient({
onerror: function(e){
alert(e.error);
},
onload: function(){
var json = this.responseText;
var response = JSON.parse(json);
if(response.logged == true){
first_name = response.f_name;
last_name = response.l_name;
email = response.email;
_this.set({
loggedIn: 1,
username: email,
realname: first_name + ' ' + last_name,
email: email,
});
_this.save();
}else{
alert(response.message);
}
},
});
auth.open('POST', url);
var params = {
usernames: username,
passwords: password,
};
auth.send(params);
alert(_this.get('email')); //alert email
},
});
When I click on login in login.xml it calls the function login in index.js. So, now my problem is that, when I click the button for the first time, I get an empty alert from alert(_this.get('email')), but then when I click the button the second time, everything works fine, it alerts the email. I have no idea what's going on. Thank you for the help.
I think I figured it out, for people that might stumble upon the same problem. I used callback function to do it.
Refer to this Titanium HTTP Request
Now my user.js looks like this:
extendModel : function(Model) {
_.extend(Model.prototype, {
login: function(username, password, callback) {
var first_name, last_name, email;
var _this = this;
var url = 'http://myurl.com/test.php';
var auth = Ti.Network.createHTTPClient({
onerror: function(e){
alert(e.error);
},
onload: function(){
var json = this.responseText;
var response = JSON.parse(json);
if(response.logged == true){
first_name = response.f_name;
last_name = response.l_name;
email = response.email;
_this.set({
loggedIn: 1,
username: email,
realname: first_name + ' ' + last_name,
email: email,
});
_this.save();
callback(foo); //whatever you want to send
}else{
alert(response.message);
}
},
});
auth.open('POST', url);
var params = {
usernames: username,
passwords: password,
};
auth.send(params);
},
});
And my login.js looks like this:
var user = Alloy.Models.user; //my user.js model
function login(e) {
if($.username.value !== '' && $.password.value !== ''){
var logged_in = user.login($.username.value, $.password.value, function(foo){
if(foo == bar)
call_another_function();
});
}else{
alert('Username and/or Password required!');
}
}
Thanks. I hope this helps.

Categories

Resources