Javascript passing variables - javascript

Okay so, I'm trying to get the facebook name and email of a user (succeed in that), and then use mandrill to email me that info. But for some reason, can't seem to get the name and email address to pass into the params object. (I deleted a lot of the facebook login stuff to make it clearer) Help!!
$(function() {
function getCurrentUserInfo() {
FB.api('/me', function(userInfo) {
console.log(userInfo.name + ': ' + userInfo.email);
temp = userInfo.email;
name = userInfo.name;
var needed = {
"name": userInfo.name,
"email": userInfo.email
}
function log(obj) {
$('#response').text(JSON.stringify(obj));
}
var m = new mandrill.Mandrill('key');
// create a variable for the API call parameters
var params = {
"message": {
"from_email":"emailf",
"to":[{"email":"emailg"}],
"subject": "New email",
"html": "*|NAME|* has the email *|EMAIL|* ",
"autotext": "true",
"track_opens": "true",
"track_clicks": "true",
"merge_vars": [
{
"rcpt": "emailrep",
"vars": [
{
"name": "NAME",
"content": "needed["name"]"
},
{
"name": "EMAIL",
"content": "needed["email"]"
}
]
}
]
}
};

You're passing strings when you need the variable:
"vars": [
{
"name": "NAME",
"content":needed["name"]
},
{
"name": "EMAIL",
"content": needed["email"]
}
]

Related

my firebase query not return value in two state

i have an funtion that return user messages for any user but when i use userid for my query firebase working true and return messages but when i pass otheruserid unfonately not return user message
firebaseGetMessages({ commit, state },otherUserId) {
let userId = state.userDetails.userId
//messagesRef = firebaseDb.ref('userMessages/' + userId ) //ok
messagesRef = firebaseDb.ref('userMessages/' + otherUserId) //not ok
messagesRef.on('child_added', snapshot => {
let messageDetails = snapshot.val()
let messageId = snapshot.key
commit('addMessage', {
messageId,
messageDetails
})
}
)
},
i trying with single qutation ("'" + otherUserId +"'")and qutation('"' + otherUserId +'"') but not effect
this is my realtime database structure
userMessages
{
"0FXpksPdL4OAf9KAXx9B0R6nzmh2": {
"-N6giImvaGnHl2L33rA9": {
"content": "test sms",
"fromId": "Yto2rkMyXJNVkWS3xAOJgUjXFzI30",
"isGroup": "true",
"messageId": "-N6giImvaGnHl2L33rA9",
"phone": "+989034015019",
"timestamp": "1657533972119",
"toId": "-N4zbr74Vw5WeYkbnVlb",
"type": "1"
},
"-N6w7t_jTLazBcbLnIau": {
"content": "Test message 1",
"fromId": "Yto2rkMyXJNVkWS3xAOJgUjXFzI3",
"messageId": "-N6w7t_jTLazBcbLnIau",
"phone": "+989034015019",
"timestamp": "1657792676492",
"toId": "0FXpksPdL4OAf9KAXx9B0R6nzmh2",
"type": "1"
},
"-N6w8651yjmhOKRHd5xG": {
"content": "Test massege 2",
"fromId": "Yto2rkMyXJNVkWS3xAOJgUjXFzI3",
"messageId": "-N6w8651yjmhOKRHd5xG",
"phone": "+989034015019",
"timestamp": "1657792676592",
"toId": "0FXpksPdL4OAf9KAXx9B0R6nzmh2",
"type": "1"
}
},
"diZUE8slUzbGvCXcmAMRdImyC7S2": {
"-N6ggkKWpAW9tQSzCKvF": {
"content": "test message group",
"fromId": "Yto2rkMyXJNVkWS3xAOJgUjXFzI3",
"messageId": "-N6ggkKWpAW9tQSzCKvF",
"phone": "+989034015019",
"timestamp": "1657533564699",
"toId": "diZUE8slUzbGvCXcmAMRdImyC7S2",
"type": "1"
}
}
}
i test this code but not worked:
let Other=otherUserId
messagesRef = firebaseDb.ref('userMessages/0FXpksPdL4OAf9KAXx9B0R6nzmh2' )
or
messagesRef = firebaseDb.ref('userMessages/'+ Other)
note that the userid store in vuex object with qutation like this "0FXpksPdL4OAf9KAXx9B0R6nzmh2" but otherUserId passed with this.$route
i not undestanding why userid returned data but otheruserid not returned data
I check traffic between web and firebase in websocket section and realize that firebase return permission denied for read other user messages
this is in inspect section - network and WS :
req1-{"t":"d","d":{"r":5,"a":"q","b":{"p":"/userMessages/340SgcUw8xaD2jjNlkpSlRVaqzc2","h":""}}}
response-1-1-{"t":"d","d":{"r":5,"b":{"s":"permission_denied","d":"Permission denied"}}}

search inside object of objects and replace value

I want to loop through all objects values inside object and replace password value with * Restricted * . I want to use recursive way tp loop over all this items
before i was targeting objects that include password value but was thinking that it can appear somewhere else inside the object entry .
this is what i tried
if (entry.requestBody) {
for (const key of Object.keys(entry.requestBody)) {
if (key.toLowerCase().includes("password")) {
entry.requestBody[key] = "***Restricted***"
}
}
if (entry.config._object) {
for (const key of Object.keys(entry.config._object)) {
if (key.toLowerCase().includes("password")) {
entry.config._object[key] = "***Restricted***"
}
}
}
}
{
"requestBody": {
"email": "ror#ror.com",
"password": "asdasdsad"
},
"code": "VALIDATION_ERROR",
"config": {
"isJoi": true,
"name": "ValidationError",
"details": [
{
"message": "\"email\" must be a valid email",
"path": [
"email"
],
"type": "string.email",
"context": {
"value": "ror#ror.com",
"key": "email",
"label": "email"
}
}
],
"_object": {
"email": "ror#ror.com",
"password": "asdasdsad"
},
"_meta": {
"source": "body"
}
}
}
}
"requestBody": {
"email": "ror#ror.com",
"password": "***Restricted***"
}
Instead of recursion, how about using regex for a quick and dirty solution:
var bodyString = JSON.stringify(entry.requestBody);
var fixedBodyString = bodyString.replace(/"password":".*"/g, '"password":"***Restricted***"');
var body = JSON.parse(fixedBodyString );
Working example:
https://playcode.io/353673?tabs=script.js,preview,console

Loop through a nested JSON object to find a value id

"results": {
"data": {
"facets": {
"60749428": {
"id": 60749428,
"name": "KC Content Content Kind"
},
"60750276": {
"id": 60750276,
"name": "KC Content Product Version"
},
"69107204": {
"id": 69107204,
"name": "KC Video Audience"
},
"69127027": {
"id": 69127027,
"name": "KC Content Kind ID"
}
}
}
}
I want to loop through this nested json object by going into the facet object and say if the name attribute is "KC Content Kind ID" then return the id for that corresponding name attribute
So after getting my api call with postman I was trying to get the corresponding id of the "KC Content Kind ID" in my success function this way, but since its not an array I was wondering if each will work in jquery.
//Get Available Kinds
function getAvailableKinds() {
$.ajax({
url: csexe + "/api/v2/facets/" +getLocationId(),
dataType: "json",
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader ("OTCSticket", getAuthToken());
},
success: function(response) {
var obj = response.results.data.facets;
$.each(obj, function(item, value){
if ( value == 'KC Content Kind ID') {
var idRequired = obj.id;
}
});
},
error: function(jqXHR, textStatus, errorThrown){
alert("An error occurred... Look at the console");
$("body").html('<p>status code: '+jqXHR.status+'</p><p>Error Thrown: ' + errorThrown + '</p><p>Response Text:</p><div>'+jqXHR.responseText + '</div>');
}
});
Just parse the string over and then do a simple loop.
var jsonObj = (JSON.parse("your json here")).data.facets;
for (i = 0; i<jsonObj.length;i++)
{
if(jsonObj[i].name == "KC Content Kind ID")
return jsobObj[i].id;
}
you can use Object.keys and find
const obj = {"results": {"data": {"facets": {"60749428": {"id": 60749428,"name": "KC Content Content Kind"},"60750276": {"id": 60750276,"name": "KC Content Product Version"},"69107204": {"id": 69107204,"name": "KC Video Audience"},"69127027": {"id": 69127027,"name": "KC Content Kind ID"}}}}};
const facets = obj.results.data.facets;
const result = Object.keys(facets).find(v => facets[v].name === 'KC Content Kind ID');
//your object keys are equal to id, you can just return key
console.log(result);
// if your object keys can be different from id you can do this
console.log(facets[result].id);
I think the easiest way to achieve this would be by using Object.values function in conjunction with Array.prototype.filter. You can then take the first item from the array returned by the filter method (since each ID should be unique) and display it's ID.
const o = { "results": { "data": { "facets": { "60749428": { "id": 60749428, "name": "KC Content Content Kind" }, "60750276": { "id": 60750276, "name": "KC Content Product Version" }, "69107204": { "id": 69107204, "name": "KC Video Audience" }, "69127027": { "id": 69127027, "name": "KC Content Kind ID"}}}}};
const [a] = Object.values(o.results.data.facets).filter(f => f.name == "KC Content Kind ID");
console.log(a.id);
var obj = {
"results": {
"data": {
"facets": {
"60749428": {
"id": 60749428,
"name": "KC Content Content Kind"
},
"60750276": {
"id": 60750276,
"name": "KC Content Product Version"
},
"69107204": {
"id": 69107204,
"name": "KC Video Audience"
},
"69127027": {
"id": 69127027,
"name": "KC Content Kind ID"
}
}
}
}
};
let facets = obj.results.data.facets;
let id;
for(let key in facets){
if(facets[key].name == 'KC Content Kind ID'){
id = facets[key].id;
break;
}
}
console.log(id);

Cannot able to add multiple fields to a document by saving the document name in dialogflow context

I have created a dialogflow bot to ask the users some questions and I need to save all the answers entered in Firestore database, I am using api v1 bot! I could able to add the fields name and answer1 by saving the Name of the document in Dialogflow context,
index.js:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
exports.dialogflowFirebaseFulfillment = functions.https.onRequest(
(request, response) => {
// console.log("function happening");
let action = request.body.result.action;
var Name = request.body.result.parameters.Name;
let params = request.body.result.parameters;
var Answer1 = request.body.result.parameters.Answer1;
var Answer2 = request.body.result.parameters.Answer2;
var Answer3 = request.body.result.parameters.Answer3;
var Answer4 = request.body.result.parameters.Answer4;
var Answer5 = request.body.result.parameters.Answer5;
var Answer6 = request.body.result.parameters.Answer6;
var Answer7 = request.body.result.parameters.Answer7;
var Answer8 = request.body.result.parameters.Answer8;
var Answer9 = request.body.result.parameters.Answer9;
var Answer10 = request.body.result.parameters.Answer10;
var Answer11 = request.body.result.parameters.Answer11;
var Answer12 = request.body.result.parameters.Answer12;
let query = request.body.result.resolvedQuery;
const parameters = request.body.result.parameters;
const inputContexts = request.body.result.contexts;
console.log("Parameters is" + params);
console.log("Answer1 is " + Answer1);
console.log("Helllo");
console.log("action is " + action);
console.log("name is:", Name);
if (action == "save.name") {
admin
.firestore()
.collection("users")
.doc(Name)
.set({
name: Name,
answer1: "",
answer2: "",
})
.then(ref => {
console.log("name saving function");
console.log("Name is added successfully", +Name);
console.log("Added new user");
});
}
if (action == "save.answer1") {
var Name;
for (
var co = 0;
inputContexts && co < inputContexts.length && !Name;
co++
) {
var context = inputContexts[co];
console.log('The input context here is ', +inputContexts[co]);
if (context.name == "question1") {
console.log("The name of the document is", +context.parameters.Name);
Name = context.parameters.Name;
}
}
console.log("name in save.answer1", Name);
admin
.firestore()
.collection("users")
.doc(Name)
.update({
answer1: Answer1
})
.then(ref => {
console.log("Updated user");
console.log("Name is " + Name);
console.log("ref id is:" + ref.id);
});
}
if (action == "save.answer2") {
var Name;
for (
var co = 0;
inputContexts && co < inputContexts.length && !Name;
co++
) {
var context = inputContexts[co];
console.log('The input context here is ', +context.name);
if (context.name == "question2") {
console.log("The context name here is", +context.name);
console.log("The name of the document is", +context.parameters.Name);
Name = context.parameters.Name;
console.log('Name inside if', +Name);
}
}
console.log("name in save.answer2", Name);
admin
.firestore()
.collection("users")
.doc(Name)
.update({
answer2: Answer2
})
.then(ref => {
console.log("Updated user");
console.log("Name is " + Name);
console.log("ref id is:" + ref.id);
});
}
}
);
I am saving the name of the document in dialogflow context, by doing so I able to save the field name and answer1 to the document, but I can't able to save answer2 by following the same technique, it throws error like:
Argument "documentPath" is not a valid ResourcePath. Path must be a non-empty string.
My json in dialogflow after saving answer1 looks like:
{
"id": "da818283-f8bf-44ee-8c86-80a69cf8128a",
"timestamp": "2018-07-18T07:33:51.743Z",
"lang": "en",
"result": {
"source": "agent",
"resolvedQuery": "I am fine",
"action": "save.answer1",
"actionIncomplete": false,
"parameters": {
"Answer1": "I am fine"
},
"contexts": [
{
"name": "question2",
"parameters": {
"Answer1": "I am fine",
"Answer1.original": "I am fine"
},
"lifespan": 1
}
],
"metadata": {
"intentId": "cf4c0b5e-b848-402a-be22-62ca26ec1d00",
"webhookUsed": "true",
"webhookForSlotFillingUsed": "false",
"isFallbackIntent": "false",
"webhookResponseTime": 10000,
"intentName": "Q-1"
},
"fulfillment": {
"speech": "Oh Well, Can you tell What is the best thing about your Companion?",
"messages": [
{
"type": 0,
"speech": "Oh Well, Can you tell What is the best thing about your Companion?"
}
]
},
"score": 1
},
"status": {
"code": 206,
"errorType": "partial_content",
"errorDetails": "Webhook call failed. Error: Request timeout."
},
"sessionId": "4967cb18-a192-0796-63ed-5ce3ec03acf9"
}
Json after inputting answer2:
{
"id": "9a9425dc-44a0-4cf6-8fa5-8d483d552c74",
"timestamp": "2018-07-18T08:40:10.86Z",
"lang": "en",
"result": {
"source": "agent",
"resolvedQuery": "I love to watch movies",
"action": "save.answer2",
"actionIncomplete": false,
"parameters": {
"Answer2": "I love to watch movies"
},
"contexts": [
{
"name": "question3",
"parameters": {
"Answer2": "I love to watch movies",
"Answer2.original": "I love to watch movies"
},
"lifespan": 1
}
],
"metadata": {
"isFallbackIntent": "false",
"webhookResponseTime": 339,
"intentName": "Q-2",
"intentId": "d15366cc-93f0-4178-975b-af8b0e182498",
"webhookUsed": "true",
"webhookForSlotFillingUsed": "false"
},
"fulfillment": {
"speech": "Oh that's cool! What is the worst thing about your partner?",
"messages": [
{
"type": 0,
"speech": "Oh that's cool! What is the worst thing about your partner?"
}
]
},
"score": 1
},
"status": {
"code": 206,
"errorType": "partial_content",
"errorDetails": "Webhook call failed. Error: 500 Internal Server Error"
},
"sessionId": "4967cb18-a192-0796-63ed-5ce3ec03acf9"
}
The problem is that you aren't storing name in any context, but you're trying to read it out of the context on the next time through. These contexts are what is storing information in between calls to your webhook, so you need to add any information you need the next time through.
Since the name of the document is something that you need to use in later responses, you need to save it.
You don't show how you're creating or sending the response, but make sure you create a context and include the name as one of the parameters.

Accessing second array in a JSON decode using Jquery

I need to access the second array from a JSON decoded string, but I am having no luck.
The entire JSON string is displayed in var RAW00, and then split into var RAW01 & var RAW02.
All 3 of these are for testing - RAW00 is identical to msg
When they are split - I can access either, depending on what variable I start of with, but when I use RAW00 I cannot access the tutor section.
I will provide more detail if required, but my question is:
How do I see and access the tutor array in the second $.each (nested) block??]
Thanks :-)
success: function(msg)
{
var test = "";
var raw00 = {
"allData": [
{
"class2": [
{
"tid": "1",
"name": "Monday 2"
},
{
"tid": "1",
"name": "Monday Test"
}
]
},
{
"tutor": [
{
"fname": "Jeffrey",
"lname": "Kranenburg"
},
{
"fname": "Jeffrey",
"lname": "Kranenburg"
}
]
}
]
};
var raw01 = {
"allData": [
{
"class2": [
{
"tid": "1",
"name": "Monday 2"
},
{
"tid": "1",
"name": "Monday Test"
}
]
}
]
};
var raw02 = {
"allData": [
{
"tutor": [
{
"fname": "Jeffrey",
"lname": "Kranenburg"
},
{
"fname": "Jeffrey",
"lname": "Kranenburg"
}
]
}
]
};
$.each(raw00.allData, function(index, entry)
{
$.each(entry.class2, function (index, data)
{
console.log(this.name);
test += '<tr><td>'+this.name+'</td>';
});
$.each(entry.tutor, function (index, data)
{
console.log(this.fname);
test += '<td>'+this.name+'</td></tr>';
});
$('#all-courses-table-content').html( test );
});
You need to check whether the current element of the array is an object with class2 property or tutor property.
$.each(raw00.allData, function(index, entry) {
if (entry.hasOwnProperty('class2')) {
$.each(entry.class2, function (index, data)
{
console.log(this.name);
test += '<tr><td>'+this.name+'</td>';
});
}
if (entry.hasOwnProperty('tutor')) {
$.each(entry.tutor, function (index, data)
{
console.log(this.fname);
test += '<td>'+this.fname+'</td></tr>';
});
}
$('#all-courses-table-content').html( test );
});
Things would probably be simpler if you redesigned the data structure. It generally doesn't make sense to have an array of objects when each object just has a single key and it's different for each. I suggest you replace the allData array with a single object, like this:
var raw00 = {
"allData": {
"class2": [
{
"tid": "1",
"name": "Monday 2"
},
{
"tid": "1",
"name": "Monday Test"
}
],
"tutor": [
{
"fname": "Jeffrey",
"lname": "Kranenburg"
},
{
"fname": "Jeffrey",
"lname": "Kranenburg"
}
]
}
};

Categories

Resources