How can I pass a variable to a URL? - javascript

I'm trying to send an email with a link in the body that contains a value retrieved from Firebase. I am successfully retrieving the value but I do not know how to append it to the link that is already listed.
Here is the code:
sendinvite() {
var user = firebase.auth().currentUser;
var uid = user.uid;
firebase.database().ref('/userlist/' + uid + '/' + 'hashKey').once('value').then(function(snapshot) {
var hashKey = (snapshot.val());
console.log(hashKey)
});
var bcc = [];
for(var e in this.emailinputs){
if (this.emailinputs[e].email==null || this.emailinputs[e].email=="" || !this.emailinputs[e].email.includes("#") || !this.emailinputs[e].email.includes("."))
{
let alert = this.alerCtrl.create({
title: 'Error!',
message: 'There was an error with an email address you entered.',
buttons: ['Ok']
});
alert.present()
}else {
bcc.push(this.emailinputs[e].email);
}
}
if(bcc.length > 0) {
let email = {
bcc: bcc,
subject: 'Nudget Invite',
body: 'Join my grocery list!',
isHtml: true
};
this.emailComposer.open(email);
}
}
I want the variable hashKey to be appended to the URL listed in the body but I'm not sure how to achieve this.
Edit 1
Updated the body to append the variable to the string. I'm not sure where I can place the hashkey from Firebase for it to be referenced properly.

The main problem I see is that you are scoping the 'hashkey' variable to just the firebase...function(snapshot) block. This should be defined at the top near the 'uid' variable, so that all of this code can reference it.
Then in you snapshot function, remove the 'var' in front of hashkey, so it just sets the existing variable.
Also, be sure to check if 'hashkey' has a non-blank value before sending the email.
HTH,
Jim

I think the problem is here:
firebase.database().ref('/userlist/' + uid + '/' + 'hashKey').once('value').then(function(snapshot) {
var hashKey = (snapshot.val());
console.log(hashKey)
});
You are creating the var named hashKey within an anonymous function then trying to access hashKey outside of that function.
Try the following instead:
var user = firebase.auth().currentUser;
var uid = user.uid;
var hashKey = null;
firebase.database().ref('/userlist/' + uid + '/' + 'hashKey').once('value').then(function(snapshot) {
hashKey = (snapshot.val());
console.log(hashKey)
});
... snip ...
body: 'Join my grocery list!',
... snip ...

Related

Resubmitting or Creating a Nested jQuery.post

I have a variable in Javascript which I am trying to pass to PHP. I have this working using jQuery.post. The issue is, the variable (linkforsharedURL) is declared within a multidimensional array and the default value is immediately sent when the jQuery.post command is executed. However the value of this variable is further modified within the function, but the modified value is not sent to PHP - the original value is sent.
A solution forward I was considering was to execute another jQuery.post just after the If statement again containing the updated 'data' array - but I don't think this would be best practice.
I did consider bringing the If statement out of the jQuery.post, however the If statement is dependent on the jQuery's response variable.
My apologies for the way I have explained the above - just trying to get my head round this particular issue.
// build data
var dataURL = dataURLs[0],
data = {
email: email,
name: name
linkforsharedURL: linkforsharedURL
};
// send data
jQuery.post("<?php echo admin_url('admin-ajax.php'); ?>", data, function(response) {
if (response.share_id !== undefined) {
var pattern = new RegExp('(share_id=).*?(&|$)'), shareUrl = window.location.href;
if (shareUrl.search(pattern) >= 0) {
shareUrl = shareUrl.replace(pattern, '$1' + response.share_id + '$2');
linkforsharedURL = shareUrl;
}
You have to create a function to call again within jQuery.post response. try the below code.
// build data
var dataURL = dataURLs[0],
data = {
email: email,
name: name,
linkforsharedURL: linkforsharedURL
};
SendDataToPhp( data );
function SendDataToPhp(){
// send data
jQuery.post("<?php echo admin_url('admin-ajax.php'); ?>", data, function(response) {
if (response.share_id !== undefined) {
var pattern = new RegExp('(share_id=).*?(&|$)'), shareUrl = window.location.href;
if (shareUrl.search(pattern) >= 0) {
shareUrl = shareUrl.replace(pattern, '$1' + response.share_id + '$2');
linkforsharedURL = shareUrl;
data.linkforsharedURL = 'updated value to send';
SendDataToPhp( data );
}
}
});
}

How do I display JSON data to an HTML DOM Element after JSON.parse()?

I have two functions I am using to pull JSON from my server side to then display it to HTML.
The first function that pulls the data from the route handler is successfully pulling the data and parsing it successfully with JSON.parse() and displaying the needed information to the console without issue. I am not having and ajax or route handling issue...
Here is how I am dealing with the JSON first in my function called "projectInfo()":
projInfo = JSON.stringify(data);
console.log("DEBUG DONE WITH CAPTURING project_info DATA: " );
// This console.log() prints the JSON string
// successfully pulled from route handler
// var projInfo is a local string var declared in the scope of
// this first function
console.log("var projInfo: " + projInfo);
// parse JSON data in projInfo and store in string var p
// string var p is a local var declared inside of the scope
// of this function
p = JSON.parse(projInfo);
console.log("Parsed Project JSON: " + p.Project);
// update "Global" pInfo with the value of the JSON data for
// "Project" as needed
pInfo = p;
console.log("What is inside of pInfo???: " + pInfo);
// This last console.log prints [object Object] to console
// How do I pul the value out of this Object?
The second function calls the first function in order to update a global variable with the parsed JSON data that I need to then display the global variable's data to the DOM element that I am trying to display.
Here is how I am trying to update my global var with a JSON Object in my function called "loginFun()":
// Call projectInfo() in order to update Global pInfo
// with the needed project info
projectInfo();
// This console.log() prints nothing...?
console.log("projectInfo var data should be aa2: " + pInfo);
document.getElementById("userBar").style.display = "";
// This is where I try to Display pInfo in the DOM but I only get Undefined...?
document.getElementById("signedinas").innerHTML = "<font face=\"verdana\" size =\"4\" color=\"white\">Logged in as: " + username + " Project: " + pInfo + " </font>";
When I JSON.parse() the data in the first function I run a console.log() statement and I get the needed data to print from a variable local to the function I am getting my JSON with using ajax and I verify that the function is in fact doing what I need so that part is good up until I get the [object Object] output.
I am having issues when I call this function from my second function to then try to use the global variable which should have the data stored.
when I try to use the global variable with the needed data I get an 'undefined'...
I have also tried returning the data that has been parsed in the first function to then storehttps://codepen.io/lopezdp/pen/owKGdJ the value returned into a local variable in the second function but I still get 'undefined'.
If you would like to see the complete code for both functions I have put them on a CodePen to make it easier at:
https://codepen.io/lopezdp/pen/owKGdJ
How can I get my Project Data to display in my DOM element?
EDIT: The JSON Data that I am using looks like this:
{"User":"aa2","Owner":"aa2_role","Status":"locked","Port":"5432","Description":"Transferred from CFS01 on Jun29","Project":"aa2","Server":"localhost"}
I rewrote your login function like this and it worked for me. I also eliminated the projectInfo() function!
var allMn = [];
var tags = [];
var pInfo = '';
function loginFun() {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
if (username == "" || password == "") {
alert("Required fields cannot be left blank.");
} else {
$.ajaxSetup({
cache: false
});
$.ajax({
type: 'GET',
url: 'http://139.169.63.170:' + port + '/login/' + username + "zlz" + password,
cache: false,
success: function (data) {
// NEED SUB ROUTINE HERE FOR AJAX CALL DPL
// Make async call to ccdd tool database to get new data
// This collects allMn[] data!!!
getMnJson();
// END SUB ROUTINE HERE
// Checks to make sure user is logged in if not
// the condition redirects user to loginFun()
if (data.search("HTTP ERROR: ") != -1) {
alert("Login Failed.");
document.getElementById('username').value = "";
document.getElementById('password').value = "";
document.getElementById('searchResults').innerHTML = "Login Failed";
document.getElementById('searchRBar').style.display = "";
loginFun();
} else {
login = 1;
// Call projectInfo() in order to update pInfo with the needed project info
//projectInfo();
var projInfo = '';
var p = '';
// Get all Mn Data on startup tp display in DOM -DPL
$.ajax({
type: 'GET',
url: 'http://139.169.63.170:' + port + '/role',
dataType: 'json',
cache: true,
success: function (data) {
// projInfo = JSON.stringify(data);
console.log("DEBUG DONE WITH CAPTURING project_info DATA: " );
// console.log("var projInfo: " + projInfo);
// parse JSON data in projInfo
p = data['Project']; //JSON.parse(projInfo);
console.log("Parsed Project JSON: " + p);
// update "Global" pInfo with the value of the JSON data for "Project" as needed
pInfo = p;
console.log("What is inside of pInfo???: " + pInfo);
document.getElementById("signedinas").innerHTML = "<font face=\"verdana\" size =\"4\" color=\"white\">Logged in as: " + username + " Project: " + pInfo + " </font>";
}
}).fail(function () {
alert("Login Failed.");
document.getElementById('username').value = "";
document.getElementById('password').value = "";
console.log("Error. /role data access Error.");
});
console.log("projectInfo var data should be aa2: " + pInfo);
document.getElementById("userBar").style.display = "";
// Display pInfo in the DOM
// document.getElementById("signedinas").innerHTML = "<font face=\"verdana\" size =\"4\" color=\"white\">Logged in as: " + username + " Project: " + pInfo + " </font>";
$("div.create").children().remove();
//-------------------------------------------------------------------END OF GLOBAL VARIABLES
$.ajaxSetup({
cache: false
});
// get table data from proxy server on port 7071 DPL
// NEED SUB ROUTINE HERE FOR AJAX CALL
// Make call to server-side code to reload JSON data into table from port 7071
pushJsonData();
// END SUB ROUTINE HERE!!!
// getTblJson();
}
}
}).fail(function () {
alert("Login Failed.");
document.getElementById('username').value = "";
document.getElementById('password').value = "";
console.log("Error. Need user Credentials");
});
}
}

localStorage is saved but cannot retain data on browser after web page reload

I am trying to save chat message on localStorage (or sessionStorage) and display on web page, I can found the key-value pair stored in Devtool -> application -> localStorage, the message value update everytime when user sends the message and display on web page. However the content gone everytime when page reload. How to solve this?
Also what I am encountering is the push() to save messages to array will replaces instead of adds value, not sure if these 2 issues are related. Thanks.
pug file
#test2(style='height:200px; width:200px; border:1px solid #ccc')
js file
$('#sendMessage').on('click', function() {
var msg = $('#message').val()
var messages = [];
console.log(typeof(messages)); //obj
messages.push(msg);
console.log(messages); //array value
if (localStorage) {
for (var i = 0; i < messages.length; i++) {
localStorage.setItem('message', msg);
}
localStorage.setItem('username', $('#username').val());
localStorage.setItem('date', currentTime());
var cUser = localStorage.getItem('username');
var cMsg = localStorage.getItem('message');
var cTime = localStorage.getItem('date');
} else {
console.log('localStorage is not supported.');
}
document.getElementById("test2").innerHTML += "<div>" + cUser + " : " + cMsg + "</div>";
// Clear the field
$('#message').val('');
}); // End click
reload page lose data
// Send Message
$('#sendMessage').on('click', function() {
// get value
var username = $('#username').val();
var msg = $('#message').val();
var time = currentTime();
//check if localStorage works and create msgArray
if (!localStorage) {
console.log('localStorage is not supported.');
} else {
//check if there is existing message array in msgArray
var msgArray = localStorage.getItem('message');
//if there is NULL, setup msgArray = [], converts a JavaScript value to a JSON string
if (JSON.stringify(msgArray) == 'null') {
msgArray = [];
} else {
//else parses a JSON string, constructing the JavaScript value or object described by the string
msgArray = JSON.parse(msgArray);
}
}
//add new message object to msgArray
var newMsg = {
msg: msg,
username: username,
time: time
};
msgArray.push(newMsg);
// stringsfy the message and store it to localStorage
localStorage.setItem('message', JSON.stringify(msgArray));
// dispaly current messages
var cMsg = JSON.parse(localStorage.getItem('message'));
// console.log(cMsg); // should shows list of array with new added message objects
// for (var i = 0, max = cMsg.length; i < max; i++) {
//document.getElementById("test2").innerHTML += "<div>" + cMsg[i].username + " : " + cMsg[i].msg + " at " + cMsg[i].time + " </div>";
$('#test2').append('<div class="well well-sm">' + cMsg[cMsg.length - 1].username + ' : ' + cMsg[cMsg.length - 1].msg + ' <span class="pull-right"><small id="date"> at ' + cMsg[cMsg.length - 1].time + '</small></span></div>');
// load the bottom of message
var objDiv = document.getElementById("chatArea");
objDiv.scrollTop = objDiv.scrollHeight;
// Clear the field
$('#message').val('');
}); // End click
I am not sure what you are trying to accomplish with your for loop, since you seem to be setting the same value as many times as you have messages (essentially that's worth nothing, setting it once should be enough)
Let's revisit your steps:
You are getting a value from an input element with id message, and saving it into the msg variable
var msg = $('#message').val()
You construct a new array, and push it in
var messages = [];
messages.push(msg);
And then you iterate the array, but re-use the msg variable
for (var i = 0; i < messages.length; i++) {
localStorage.setItem('message', msg);
}
So essentially, you did this:
localStorage.setItem('message', $('#message').val());
and nothing more. Maybe you wanted to get the array of messages first, and then add the new message to it, rather something like the following
function addMessage() {
// get the potential array
var messages = JSON.parse( localStorage.getItem('message') || '[]' );
// add the message
messages.push($('#message').val());
// save the array as a string, using JSON.stringify
localStorage.setItem('message', JSON.stringify( messages));
// empty the message value
$('#message').val('');
console.log(messages);
}
If you want to save some chat messages, I think you should make sure that all message are properly linked with the author's username and the time it was wrote.
You tried an array... For the messages, but not for the other infos.
And you misused the array.
LocalStorage will only store a string.
Well... I think it can store objects too... But It is a habit of mine to always store strings.
This way, it always can be console logged fast, instead of bugging...
So stringify the array before saving it.
And when you retreive it,you have to parse it back to an array to be able to push a new message into it.
Ok... So will you try to synchronize 3 or more arrays?
I suggest ONE array of objects.
Each objects containing all the relevant infos linked to a particular message.
See comments in code.
$('#sendMessage').on('click', function() {
// ...
var chatWindow = $("#chatWindow");
// Get all values now.
var msg = $('#message').val();
var username = $('#username').val();
var time = moment().format("hh:mm:ss");
if (!localStorage) {
console.log('localStorage is not supported.');
}else{
// Retreive previous messages
var messageArray = localStorage.getItem('message');
// If there was none, set it as an array
if(JSON.stringify(messageArray) == "null"){
console.log(JSON.stringify(messageArray));
messageArray = [];
// If there was, get them back from string to an array of objects.
}else{
messageArray = JSON.parse(messageArray);
}
// Set the new message object.
var newMsg = {msg:msg,
time:time,
username:username
}
// Insert the new message object in the array.
messageArray.push(newMsg);
// Save the array as a string.
var messagesStringified = JSON.stringify(messageArray);
localStorage.setItem('message', messagesStringified);
// I suppose that showing the messages from what is saved re-assures you about the saving...
var cMsg = localStorage.getItem('message');
// Empty chatWindow
chatWindow.empty();
// Loop through the messages.
var allMessages = JSON.parse(cMsg);
for(i=0;i<allMessages.length;i++){
chatWindow.append("<div>" +
allMessages[i].time +
" | "+ allMessages[i].username +
" : " + allMessages[i].msg + "</div>");
}
console.log(JSON.stringify(messageArray));
// Clear the field
$('#message').val('');
}
}); // End click
$('#clear').on('click', function() {
localStorage.clear();
});
Have a look on **CodePen.

Sava Data to a variable Place [Firebase]

I want to write some User Data to a variable place. But I don't know how I can tell this to Firebase. The normal save function doesn't work with a variable save location. Like in the example below I want to save the data on a variable save location.
function Writevariabledata(userId,data)
{
firebase.database().ref('user/testdata/' + userId).set({
$userId: data
});
}
this works for me
function Writevariabledata() {
var name = document.getElementById("name");
var firebaseref = firebase.database().ref("user/testdata/" + userId);
var messagetext = {};
messagetext.cat_name = name.value;
firebaseref.push().set(messagetext);
window.alert('Inserted Successfully..');

Parse.com Js Sdk + Angular pointers

What if I have an array of events that I want users to be able to rsvp for? Essentially needing the data of the "user" who clicked "rsvp", and the "title" of the "event" that they've rsvp'd for. Could I make a pointer in a Agree class that includes the user's name/id and another pointer that includes the title of the event rsvp'd for? Is there a way to somehow use Angular to add code to the "Agree" class with a form?
User Class:
objectId
username
password
Agree Class:
objectId
username-(current user)
Comments Structure:
Event Class:
objectId-
title-(Need this title)
description-
date-
Please help me understand how to make this work..Thanks!
$scope.getAgree = function(){
var Agree = Parse.Object.extened("Agree");
var query = new Parse.Query("Agree");
query.include("userName");
query.find().then(function(results){
//Go through each in Array
var rsvpOjectArray = new Array();
or(i in results){
//Set Object to current RsvpObject
var obj = results[i];
//Get user
var userName = obj.get("userName").get("username");
rsvpOjectArray.push({
user: {userName
}
});
}
});
};
$scope.makeAgree = function(){
var Agree = Parse.Object.extend("Agree");
var agree = new Agree();
var user = new Parse.Object("Agree");
agree.set("userName", Parse.User.current());
agree.save(null, {
success: function(rsvp) {
// Hooray! Let them use the app now.
alert("success!");
},
error: function(rsvp, error) {
// Show the error message somewhere and let the rsvp try again.
alert("Error: " + error.code + " " + error.message);
}
});
};

Categories

Resources