i have an application that allows the user to send a text message by entering a phone number into the input field. but the text message is set to just say "hello". how can i allow the user to enter what they want the text message to say. heres the code
JS
app.get("/:data", function(req, resp){
var accountSid = '*******************'
var authToken = '*********************'
const client = require('twilio')(accountSid, authToken);
client.messages.create({
to: req.params.data,
from: '**********',
body: "Hello"
}, function(err, message) {
if(err) {
console.log(err);
} else {
console.log(message.sid);
}
});
HTML
<input type="text" placeholder="Enter your number" id="inputNum" />
<button id="submitNum">Enter</button>
<script>
submitNum.addEventListener("click", function(){
var inputNum = document.getElementById("inputNum");
var submitNum = document.getElementById("submitNum");
var phoneNumber = inputNum.value;
fetch(" https://*******************.com/"
+ phoneNumber).then((resp)=>{
console.log(resp);
});
});
Twilio developer evangelist here.
To allow your user to enter the message too, you need to add an extra field to your HTML form and then add that field to the API request too. I would also suggest not adding the phone number to the path of the URL, but to query parameters instead. So, taking your HTML first, I'd change it to this:
<input type="text" placeholder="Enter your number" id="inputNum" />
<textarea name="inputMessage" id="inputMessage"></textarea>
<button id="submitNum">Enter</button>
<script>
var inputNum = document.getElementById("inputNum");
var inputMessage = document.getElementById("inputMessage");
var submitNum = document.getElementById("submitNum");
submitNum.addEventListener("click", function(){
var phoneNumber = inputNum.value;
var message = inputMessage.value;
var query = "phoneNumnber=" + encodeURIComponent(phoneNumber);
query += "&message=" + encodeURIComponent(message);
fetch(" https://*******************.com/sendMessage?" + query).then((resp)=>{
console.log(resp);
});
});
</script>
Then, you'll need to update your server to use the message variable and the sendMessage endpoint. I also suggest you send a response back, so that your front end isn't left hanging. Like this:
app.get("/sendMessage", function(req, resp){
var accountSid = '*******************'
var authToken = '*********************'
const client = require('twilio')(accountSid, authToken);
client.messages.create({
to: req.params.data,
from: '**********',
body: req.params.message
}, function(err, message) {
if(err) {
console.log(err);
resp.setStatus(200).send();
} else {
console.log(message.sid);
resp.setStatus(500).send();
}
});
});
Let me know if that helps at all.
Related
I'm trying to allow users to type a search query into a box on an index.html page and have it send them to a results.html page with results displayed.
Currently I have this working only on an index.html page where the old HTML is removed and replaced with the search results.
//Pertinent Node code:
app.get('/', function(req, res){
res.header("Access-Control-Allow-Origin", "*");
res.redirect('index.html');
});
// A search box in index.html calls the /search below
app.get('/search', function (req, res) {
res.header("Access-Control-Allow-Origin", "*");
const item_id = req.query.item_id;
var json = {};
var sql_query = "a SQL query";
var result = connection.query(sql_query, function(err, result, fields) {
if (err) throw err;
json["result"] = result;
console.log("Sent JSON to client");
res.send(JSON.stringify(json));
});
})
//Client-side:
function get() {
var search = document.getElementById("search").value;
// Validate input to prevent injections
var new_search = search.replace("<", "");
var validated = new_search.replace(">", "");
var url = host + "/search?search=" + validated;
fetch(url, {method : 'GET'})
.then(checkStatus)
.then(function(responseText) {
var json = JSON.parse(responseText);
displaySearchResults(json, search);
})
.catch(function(error) {
});
}
What I'm trying to do is similar to what you might see on Google where clicking search send you to a new page with a url like: "https://www.google.com/searchresults?query=bicycles" that displays a different HTML page from index.html (such as results.html) with the JSON from index.html being moved to and processed in results.html.
How can I make this happen?
Adding some details to what Brad kindly mentioned in comments.. The full solution is:
<form action="search.html" method="GET" name="search">
Then in the Javascript file for search.html, access the form data with:
var search = window.location.search;
If you need to get the "?search=" out of the data, instead use:
var search = window.location.search.replace("?search=", "");
I'm working on a chatroom page where you first set your username and it sets the username value inside cookies. after this it loads different input boxes where you can send messages from in realtime. At this point you can reload the page and it will give you a pop-up which will display a welcome back message with the name value saved inside the cookies, which will also just set it as the username again and load the chatting page.
The problem is that I want to be able to prevent multiple duplicates of a name to be set from the username setting input field, but allow the username be set multiple times inside the array via cookies.
this function sets the original username:
//index.html
function setUsername() {
var textbox = document.getElementById("name");
var txtboxval = textbox.value;
if(textbox.value.length <= 20 && textbox.value.length >= 4){
socket.emit('setUsername', document.getElementById('name').value);
setCookie("username", txtboxval, 30);
socket.on('userExists', function(data) {
});
}
else{
alert("The name has to be at least 4 characters long");
return false;
}
};
and these two set it on cookie load:
//index.html
function setUsername2() {
var nimi = getCookie('username');
socket.emit('setUsername', nimi);
}
function checkCookie() {
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
setUsername2();
document.body.innerHTML = '<div class="wrapper"><div class="messagebox"><input type = "text" id = "message" placeholder = "Write your message here">\
<button type = "button" id="sending" name = "button" onclick = "sendMessage()">Send</button></div>\
<div id = "message-container"></div></div>';
}
}
now this here actually sets the username into the array where it digs it from on the index.html page:
//app.js
users = [];
io.on('connection', function(socket){
console.log('an user connected');
console.log(users);
socket.on('setUsername', function(data) {
console.log(data);
users.push(data);
socket.emit('userSet', {username: data});
console.log(users);
});
I would like this piece of code to run when first setting the username, but not when it loads from cookies:
//app.js
if(users.indexOf(data) > -1) {
socket.emit('userExists', data + ' Username is already taken.');
} else {
users.push(data);
socket.emit('userSet', {username: data});
console.log(users);
}
Is there something I'm missing on why I can't get it to work as I would like it to? If something is unclear please ask.
You could get this done triggering your 'setUsername' using an object {name: string, cookie: boolean} instead of the username only, like i did here:
function setUsername() {
var textbox = document.getElementById("name");
var txtboxval = textbox.value;
if(textbox.value.length <= 20 && textbox.value.length >= 4){
socket.emit('setUsername', {name: document.getElementById('name').value, cookie: false});
setCookie("username", txtboxval, 30);
socket.on('userExists', function(data) {
// ########## you could add your 'already taken'-message here. :) ##########
console.log(data);
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
// this 'deletes' the cookie.
});
} else {
alert("The name has to be at least 4 characters long");
return false;
}
}
function setUsername2() {
var nimi = getCookie('username');
socket.emit('setUsername', {name: nimi, cookie: true});
}
function checkCookie() {
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
setUsername2();
document.body.innerHTML = '<div class="wrapper"><div class="messagebox"><input type = "text" id = "message" placeholder = "Write your message here">\
<button type = "button" id="sending" name = "button" onclick = "sendMessage()">Send</button></div>\
<div id = "message-container"></div></div>';
}
}
users = [];
io.on('connection', function(socket){
console.log('an user connected');
console.log(users);
socket.on('setUsername', function(data) {
console.log(data);
if(!data.cookie && users.indexOf(data.name) > -1) {
socket.emit('userExists', data.name + ' Username is already taken.');
} else {
users.push(data.name);
socket.emit('userSet', {username: data.name});
console.log(users);
}
});
});
If i got it right, and you want to distinct two activities - setting username from cookie and setting username from input#name -, so you just have to emit userExists with some additional data, with some flag, like cookie (which will mean that you're setting the value from cookie) or user_input (which will mean that you're setting the value from the input field), like this:
socket.emit('userSet', {username: data.name, user_input: true});
Hey guys I am trying to make a custom registration form with the accounts-password package but i get an error in the console : Error invoking Method 'insertUser': Internal server error [500]and on the server side :
=> Meteor server restarted
I20170209-20:25:53.029(1)? Exception while invoking method 'insertUser' ReferenceError: password is not defined
This is my client side code :
Template.Anmeldung.events({
"submit .add-benutzer": function(event){
var Vorname = event.target.Vorname.value;
var Nachname = event.target.Nachname.value;
var Geburtsdatum = event.target.Geburtsdatum.value;
var Email = event.target.Email.value;
var Passwort = event.target.Passwort.value;
Meteor.call('addBenutzer', Vorname, Nachname, Geburtsdatum, Vorname)
Meteor.call('insertUser', Email, Passwort);
event.target.Vorname.value = "";
event.target.Nachname.value = "";
event.target.Geburtsdatum.value = "";
event.target.Email.value = "";
event.target.Passwort.value = "";
FlowRouter.go('/meineEvents');
return false;
}
});
and my server side code :
Meteor.methods({
insertUser(emailVar, paswordVar){
Accounts.createUser(emailVar, passwordVar);
}
});
Thank you for every help ;)
It is just that you use the Accounts.createUser wrong, it should be this:
Meteor.methods({
insertUser(emailVar, paswordVar){
Accounts.createUser({
email: emailVar,
password: passwordVar
});
}
});
You don't need to call Accounts.createUser on the server in a Meteor method. In fact, doing so is dangerous because you are passing the password from the client to the server without encrypting it.
I recommend you read the docs for the functions you use: Link
In this case you can just use do
Template.Anmeldung.events({
"submit .add-benutzer": function(event){
var Vorname = event.target.Vorname.value;
var Nachname = event.target.Nachname.value;
var Geburtsdatum = event.target.Geburtsdatum.value;
var Email = event.target.Email.value;
var Passwort = event.target.Passwort.value;
Meteor.call('addBenutzer', Vorname, Nachname, Geburtsdatum, Vorname)
Accounts.createUser({ email: Email, password: Passwort} , (error) => {
if(error) {
alert(error.reason);
}
});
[...]
}
});
As a side note, in some cases you need to create a user on the server. In these cases you can use the Accounts._hashPassword() on the client before sending the password to the server. This ensures the password isn't sent in plain text.
Using Slack, and trying to set up an Outgoing Webhook to send an email when a user types in a certain keyword. Slack sends a POST in the following format:
token=XXXXXXXXXXXXXXXXXX
team_id=T0001
team_domain=example
channel_id=C2147483705
channel_name=test
timestamp=1355517523.000005
user_id=U2147483697
user_name=Steve
text=atsk: ticket#; ticket details
trigger_word=atsk:
It sends this POST to a URL that is set up with this Google script:
function autoMail(sendmail) {
var params = sendmail.parameters;
if (params.token == "XXXXXXXXXXXXXXXXXX") {
var textRaw = String(params.text).replace(/^\s*atsk\s*:*\s*/gi,'');
var text = textRaw.split(/\s*;\s*/g);
var email = "example#gmail.com";
var subject = text[0];
var message = text + "Ticket created by Autoslack Bot";
MailApp.sendEmail(email, subject, message);
} else {
return;
}
}
Which is published as a Web App and set to run as 'Anyone, even anonymous' and been granted permission to use my Google Email.
So if someone types 'atsk: T12345678; User has an issue.' it should send an email to 'example#gmail.com' with the subject 'T12345678' and the message 'T12345678; User has an issue. Ticket created by Autoslack Bot'
I thought this was set up correctly, but I cannot get an email to send to the specified address. Can someone help, please?
I would suggest to create a test function to check the Apps script part on its own like this :
function testAutoMail() {
var parameters={};
parameters['text']='atsk: T12345678; User has an issue.';
parameters['token']="XXXXXXXXXXXXXXXXXX";
var arg = {};
arg['parameters']=parameters;
autoMail(arg);
}
function autoMail(sendmail) {
var params = sendmail.parameters;
if (params.token == "XXXXXXXXXXXXXXXXXX") {
var textRaw = String(params.text).replace(/^\s*atsk\s*:*\s*/gi,'');
var text = textRaw.split(/\s*;\s*/g);
var email = "example#gmail.com";
var subject = text[0];
var message = text + "Ticket created by Autoslack Bot";
Logger.log('MailApp.sendEmail('+email+', '+subject+', '+message+')');
} else {
return;
}
}
And look at the Logger to see if it works.
How can I display POST data value from one HTML page on other HTML page without using any template engine ? Below is code fro posting data :
app.post('/RegistrationSuccessPage', function (req, res) {
var uname = req.body.username
var pwd = req.body.pwd
var emailAddress = req.body.email
postData = uname+","+pwd+","+emailAddress
console.log(postData);
res.sendFile( __dirname + "/RegistrationSuccessPage.html",postData);
});
And following is HTML where I have to show the values:
<body>
<div>
<form>
<div align="center">
<label>Below are the details</label><br><br>
<label id="uname">Username *: (username_value_to_be_shown_here)</label><br><br>
<label id="email">Email Address *: (email_value_to_be_shown_here)</label><br><br>
<br><br>
</div>
</form>
</div>
</body>
If you change username_value_to_be_shown_here by $USER and email_value_to_be_shown_here by $EMAIL you can use string replacement like this:
var fs = require('fs');
app.post('/RegistrationSuccessPage', function (req, res) {
var data = {
USER: req.body.username,
EMAIL: req.body.email
};
fs.readFile( __dirname + '/RegistrationSuccessPage.html', 'utf8', function(err, content) {
var result = content;
for (var key in data) {
result = result.replace("$" + key, data[key]);
}
res.send(result);
});
});
if the $VAR is in more then one place you will need to use regex like:
result = result.replace(new RegExp("\\$" + key, "g"), data[key]);