jQuery/Ajax form success message - forms

I have a couple of forms on a site I'm working on and the script that controls them doesn't include a success message, so when they're submitted the input data just disappears and the user doesn't know if it's been actually sent or not. I've looked around a bit for answers, but because this file controls an email submission form, a contact form, and a twitter feed, it's a bit much for me to see what's what.
Here's the code, I'd just like to let users know that their message has been sent for both the email input form and the contact form. I appreciate any help that's out there!
$(document).ready(function() {
//Set default hint if nothing is entered
setHints();
//Bind JavaScript event on SignUp Button
$('#signUp').click(function(){
signUp($('#subscribe').val());
});
//Bind JavaScript event on Send Message Button
$('#sendMessage').click(function(){
if(validateInput()){
sendMail();
}else
{
alert('Please fill all fields to send us message.');
}
});
//Load initial site state (countdown, twitts)
initialize();
});
var setHints = function()
{
$('#subscribe').attachHint('Enter your email to be notified when more info is available');
$('[name=contact_name]').attachHint('Name');
$('[name=contact_email]').attachHint('Email');
$('[name=contact_subject]').attachHint('Subject');
$('[name=contact_message]').attachHint('Message');
};
var signUp = function(inputEmail)
{
var isValid = true;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test(inputEmail)){
isValid = false;
alert('Your email is not in valid format');
}
if(isValid){
var params = {
'action' : 'SingUp',
'email' : inputEmail
};
$.ajax({
type: "POST",
url: "php/mainHandler.php",
data: params,
success: function(response){
if(response){
var responseObj = jQuery.parseJSON(response);
if(responseObj.ResponseData)
{
$('#subscribe').val('');
}
}
}
});
}
};
var initialize = function()
{
var params = {
'action' : 'Initialize'
};
$.ajax({
type: "POST",
url: "php/mainHandler.php",
data: params,
success: function(response){
if(response){
var responseObj = jQuery.parseJSON(response);
if(responseObj.ResponseData)
{
$('ul.twitts').empty();
if(responseObj.ResponseData.Twitts){
$('a.followUsURL').attr('href','http://twitter.com/#!/'+responseObj.ResponseData.Twitts[0].Name);
$.each(responseObj.ResponseData.Twitts, function(index, twitt){
var twitterTemplate = '<li>'
+ '#{0}'
+ '{2}'
+ '<span class="time">{3}</span>'
+ '</li>';
$('ul.twitts').append(StringFormat(twitterTemplate, twitt.Name, twitt.StatusID, twitt.Text, twitt.Date));
});
}
if(responseObj.ResponseData.Start_Date)
{
setInterval(function(){
var countDownObj = calculateTimeDifference(responseObj.ResponseData.Start_Date);
if(countDownObj){
$('#days').text(countDownObj.Days);
$('#hours').text(countDownObj.Hours);
$('#minutes').text(countDownObj.Minutes);
$('#seconds').text(countDownObj.Seconds);
}
}, 1000);
}
}
}
}
});
};
var validateInput = function(){
var isValid = true;
$('input, textarea').each(function(){
if($(this).hasClass('required'))
{
if($(this).val()!=''){
if($(this).hasClass('email'))
{
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test($(this).val())){
isValid = false;
alert('Your email is not in valid format');
}
}
}else
{
isValid = false;
}
}
});
return isValid;
};
var resetInput = function(){
$('input, textarea').each(function() {
$(this).val('').text('');
});
};
var sendMail = function(){
var params = {
'action' : 'SendMessage',
'name' : $('[name=contact_name]').val(),
'email' : $('[name=contact_email]').val(),
'subject' : $('[name=contact_subject]').val(),
'message' : $('[name=contact_message]').val()
};
$.ajax({
type: "POST",
url: "php/mainHandler.php",
data: params,
success: function(response){
if(response){
var responseObj = jQuery.parseJSON(response);
if(responseObj.ResponseData)
$('label.sendingStatus').text(responseObj.ResponseData);
}
resetInput();
$('#sendMail').removeAttr('disabled');
},
error: function (xhr, ajaxOptions, thrownError){
//xhr.status : 404, 303, 501...
var error = null;
switch(xhr.status)
{
case "301":
error = "Redirection Error!";
break;
case "307":
error = "Error, temporary server redirection!";
break;
case "400":
error = "Bad request!";
break;
case "404":
error = "Page not found!";
break;
case "500":
error = "Server is currently unavailable!";
break;
default:
error ="Unespected error, please try again later.";
}
if(error){
$('label.sendingStatus').text(error);
}
}
});
};
var calculateTimeDifference = function(startDate) {
var second = 1000;
var minute = second * 60;
var hour = minute * 60;
var day = hour * 24;
var seconds = 0;
var minutes = 0;
var hours = 0;
var days = 0;
var currentDate = new Date();
startDate = new Date(startDate);
var timeCounter = startDate - currentDate;
if (isNaN(timeCounter))
{
return NaN;
}
else
{
days = Math.floor(timeCounter / day);
timeCounter = timeCounter % day;
hours = Math.floor(timeCounter / hour);
timeCounter = timeCounter % hour;
minutes = Math.floor(timeCounter / minute);
timeCounter = timeCounter % minute;
seconds = Math.floor(timeCounter / second);
}
var tDiffObj = {
"Days" : days,
"Hours" : hours,
"Minutes" : minutes,
"Seconds" : seconds
};
return tDiffObj;
};
var StringFormat = function() {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var regExpression = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(regExpression, arguments[i + 1]);
}
return s;
}

You need to hook into the success callbacks of each of the $.ajax calls. You can create a method that will show a message for those:
For example, your signUp function's success callback could look like:
success: function(response){
if(response){
var responseObj = jQuery.parseJSON(response);
if(responseObj.ResponseData)
{
$('#subscribe').val('');
showMessage('Your subscription was received. Thank you!');
}
}
}
And you just create a method that will show the message to the user
var showMessage = function (msg) {
// of course, you wouldn't use alert,
// but would inject the message into the dom somewhere
alert(msg);
}
You would call showMessage anywhere the success callback was fired.

You can add your success notifing code in each of the $.ajax success handlers.

Related

Salesforce lightning input's element.set not working anymore after summer 18 release

I am using below snippet to check for valid phone number format and then trying to set the formatted value to the current input element. But after summer 18 release I'm unable to set input with new formatted value.
TestApp
<aura:application extends="force:slds">
<lightning:input type="text" label="Num" aura:id="ele" onchange="
{!c.changeNum}" />
</aura:application>
Controller:
({
changeNum : function(component, event, helper) {
helper.changeNum(component, event);
}
})
Helper:
({
changeNum : function(component, event) {
var element = event.getSource();
var phonenumber = element.get("v.value");
if(phonenumber){
var updatedValue = phonenumber.replace(/-/g, "");
if(/^\d{10}$/.test(updatedValue)){
phonenumber = updatedValue.match(new RegExp('\\d{4}$|\\d{3}', 'g')).join("-");
}
else{
var x = phonenumber.replace(/[^0-9._-]/g, "").replace(/ +/, " ");
phonenumber = x;
if(!/^[0-9-]+$/.test(phonenumber.slice(-1))){
phonenumber = phonenumber.slice(0, -1);
}
}
}
console.log(phonenumber);
element.set('v.value', phonenumber);
}
})
element.set is not able to update the formatted value. The lightning input element is still able to accept alphabets.
We can solve the issue by using Promise
({
handleInputChange : function(component, event) {
try {
var element = event.getSource();
var inputValue = element.get("v.value");
var formattedValue;
var chkPattern = new Promise(
function (resolve, reject) {
if (inputValue) {
formattedValue = inputValue.replace(/[^0-9-]/g, "").replace(/ +/, " ");
resolve(formattedValue); // fulfilled
} else {
var reason = new Error('kitten is not happy');
reject(reason); // reject
}
}
);
chkPattern.then(function (fulfilled) {
element.set('v.value', fulfilled);
}).catch(function (error) {
console.log(error.message);
});
} catch(e) {
this.consoleLog(e.stack, true)
}
}
})

Github api get last Users that committed

I want to get the last users exe. last 100 users that committed on github regardless of repo. I've looked around the github api but can't find the specific api call.
You can use Github Events API and filter PushEvent :
https://api.github.com/events?per_page=100
User(s) who have made the last 100 commits on Github
As a PushEvent may have multiple commits, you will have to sum the size for each PushEvent until you reach 100. Note that you also need to exclude PushEvent with 0 commit. You will also have to manage pagination as you can request 100 events max at once (if one request is not enough to get 100 commits).
An example using nodeJS :
var request = require("request");
const maxCommit = 100;
const accessToken = 'YOUR_ACCESS_TOKEN';
function doRequest(page){
return new Promise(function (resolve, reject) {
request({
url: 'https://api.github.com/events?per_page=100&page=' + page,
headers: {
'User-Agent': 'Some-App',
'Authorization': 'Token ' + accessToken
}
}, function (err, response, body) {
if (!err) {
resolve(body);
} else {
reject(err);
}
});
})
}
async function getEvents() {
var commitCount = 0;
var page = 1;
var users = [];
while (commitCount < maxCommit) {
var body = await doRequest(page);
var data = JSON.parse(body);
var pushEvents = data.filter(it => it.type == 'PushEvent' && it.payload.size > 0);
commitCount += pushEvents.reduce((it1, it2) => it1 + it2.payload.size, 0);
users = users.concat(pushEvents.map(event => ({
login: event.actor.login,
commitCount: event.payload.size
})));
page++;
}
var count = 0;
for (var i = 0; i < users.length; i++) {
count += users[i].commitCount;
if (count >= maxCommit){
users = users.slice(0, i + 1);
break;
}
}
console.log(users);
}
getEvents();
Last 100 Users who have pushed commits on Github
The only things that changes is that we only check that size field is > 0 and build a map for distinct user.
An example using nodeJS :
var request = require("request");
const maxUser = 100;
const accessToken = 'YOUR_ACCESS_TOKEN';
function doRequest(page){
return new Promise(function (resolve, reject) {
request({
url: 'https://api.github.com/events?per_page=100&page=' + page,
headers: {
'User-Agent': 'Some-App',
'Authorization': 'Token ' + accessToken
}
}, function (err, response, body) {
if (!err) {
resolve(body);
} else {
reject(err);
}
});
})
}
async function getEvents() {
var page = 1;
var users = {};
while (Object.keys(users).length < maxUser) {
var body = await doRequest(page);
var data = JSON.parse(body);
var pushEvents = data.filter(it => it.type == 'PushEvent' && it.payload.size > 0);
for (var i = 0; i < pushEvents.length; i++) {
users[pushEvents[i].actor.login] = pushEvents[i].payload.size;
if (Object.keys(users).length == maxUser) { 
break;
}
}
page++;
}
console.log(users);
}
getEvents();

how to collect data from user with the facebook messenger bot api in node js

I am building a messenger bot in node. I want it to collect user input data and have a conversation or ask questions, but the code I have doesn't work. the part that does not work is it only continues to the next else if block if i type the same code. and second the array is not capturing the text after the first if statement. Is there a better way to do it? Could someone provide code?
My code is below. what i want is like in this iimage:
var currentbot = 0;
var awnswers = [];
app.post('/webhook', function(req, res) {
var events = req.body.entry[0].messaging;
for (i = 0; i < events.length; i++) {
var event = events[i];
if (event.message && event.message.text) {
var text = event.message.text;
if (text == "hi") {
start(event.message.text, event.sender.id);
}
}
}
res.sendStatus(200);
});
var awnswers = [];
function start(text, id) {
if (count == 0) {
sendTextMessage('hello lets order!', id);
arr.push(text);
console.log(awnswers);
count = 1;
} else if (count == 1) {
sendTextMessage('what size do you want?', id);
arr.push(text);
console.log(awnswers);
count = 2;
} else if (count == 2) {
sendTextMessage('its on its way!', id);
arr.push(text);
console.log(awnswers);
count = 0;
}
}
function sendTextMessage(messageText, recipientId) {
var messageData = {
recipient: {
id: recipientId
},
message: {
text: messageText
}
};
callSendAPI(messageData);
}
function callSendAPI(messageData) {
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: {
access_token: process.env.access_token
},
method: 'POST',
json: messageData
}, function(error, response, body) {
if (!error && response.statusCode == 200) {
var recipientId = body.recipient_id;
var messageId = body.message_id;
console.log("Successfully sent generic message with id %s to recipient %s", messageId, recipientId);
} else {
console.error("Unable to send message.");
console.error(response);
console.error(error);
}
});
}
The main issues I think I see are:
Start() is only called when text == hi
Count is not defined
You're pushing to the array 'arr' not, awnswers
You can fix these by:
Calling start() on every message
Defining count like var count = 0; at the top of your file, next to var currentbot
awnswers.push(text);

Restart progress indicator button selection press in SAPUI5?

I am new to SAPUI5. I have two controllers participantList.controller.js and Topic.controller.js. I have defined function called refreshData in participantList.js and I am trying to call that function Topic.Controller.js. Overall, I have progress indicator set up at top in participantList view. So, every time when I navigate from Topic view to participant view by selecting topic on topic view, I want to restart progress indicator that's on participant view. Please help!
Here is code for ParticipantList.controller.js:
var reset;
var list;
sap.ui.define([
"fiveminuteapp/controller/BaseController",
"fiveminuteapp/controller/Topic.controller"
],
function(BaseController, participant) {
"use strict";
return BaseController.extend("fiveminuteapp.controller.participant.ParticipantList", {
onInit: function() {
var topicheader = this.byId("employeeListPage");
topicheader.setTitle(topic);
this.listfunction();
this.testFunction();
},
refreshData: function() {
clearInterval(reset);
lTime.setText("5:00");
setInterval(reset);
},
testFunction: function() {
var setMinutes = 5;
var originalTime = setMinutes * 60;
var time = originalTime;
var lTime = this.byId("labelTimeLeft");
var progress = this.byId("progressIndicator");
reset = setInterval(function() {
var minutes;
var seconds;
if (time > -1) {
minutes = Math.floor(time / 60);
seconds = time % 60;
time = time - 1;
if (minutes < 10 && seconds < 10) {
lTime.setText("0" + minutes + ":" + "0" + seconds);
} else if (minutes < 10) {
lTime.setText("0" + minutes + ":" + seconds);
} else if (seconds < 10) {
lTime.setText(minutes + ":" + "0" + seconds);
}
progress.setPercentValue((time / originalTime) * 100);
} else {
clearInterval(reset);
lTime.setText("5:00");
setInterval(reset);
if(lTime.getText() === "00:00"){
$.ajax({
type: "post",
data:{username: username},
url:"/fiveminuteapp/AddPoints"
})
}
}
}, 1000);
},
listfunction: function(){
var test = this.getView().byId("participantList");
setInterval(function(){
var aData = $.ajax({
type: "get",
data:{topic : topic},
contentType : "application/json",
url:"/fiveminuteapp/RetrieveName",
dataType: "json",
async:false,
}).responseJSON;
var oModel = new sap.ui.model.json.JSONModel(aData);
test.setModel(oModel, 'listmodel')
},5000)
}
});
});
and here is code for Topic.Controller.js:
sap.ui.define([
"fiveminuteapp/controller/BaseController",
"fiveminuteapp/controller/participant/ParticipantList.controller"
], function(BaseController, participant) {
"use strict";
return BaseController.extend("fiveminuteapp.controller.Topic", {
onNavToParticipant: function(oEvent) {
var otime = window.originalTime;
var oItem = oEvent.getSource();
var oContext = oItem.getBindingContext("topics");
var topicSelected = oContext.getProperty("TopicChoices");
topic = topicSelected;
$.ajax({
type: "post",
data:{username: username, topic : topic},
url:"/fiveminuteapp/InsertTopic"
})
this.getRouter().navTo("participantList");
var time = participant.refreshData();
//sap.ui.controller("ParticipantList.controller.js").refreshData();
}
});
});
Topic view
Participant view
I assume you are using Routing in your application. If yes, you can attach route pattern match handlers to specific routes, which handlers will be invoked by the framework every time when the specific route has been matched.
Register a handler in your ParticipantList.controller.js onInit() method:
oRouter.getRoute("participantList").attachPatternMatched(this._onRouteMatched, this);
Then implement the handler function itself in ParticipantList.controller.js with name _onRouteMatched():
_onRouteMatched: function (oEvent) {
this.refreshData();
}
More details can be found in the official UI5 documentation.

chrome.serial receiveTimeout Not working.

Below code is a copy with minor edits from https://github.com/GoogleChrome/chrome-app-samples/tree/master/serial/ledtoggle. I am able to send a byte and receive a reply. I am not able to get an TimeoutError event in case of reply is not sent by the client. I have set timeout to 50 ms.
this.receiveTimeout = 50;
Entire code follows.
const DEVICE_PATH = 'COM1';
const serial = chrome.serial;
var ab2str = function(buf) {
var bufView = new Uint8Array(buf);
var encodedString = String.fromCharCode.apply(null, bufView);
return decodeURIComponent(escape(encodedString));
};
var str2ab = function(str) {
var encodedString = unescape((str));
var bytes = new Uint8Array(1);
bytes[0] = parseInt(encodedString);
}
return bytes.buffer;
};
var SerialConnection = function() {
this.connectionId = -1;
this.lineBuffer = "";
this.receiveTimeout =50;
this.boundOnReceive = this.onReceive.bind(this);
this.boundOnReceiveError = this.onReceiveError.bind(this);
this.onConnect = new chrome.Event();
this.onReadLine = new chrome.Event();
this.onError = new chrome.Event();
};
SerialConnection.prototype.onConnectComplete = function(connectionInfo) {
if (!connectionInfo) {
log("Connection failed.");
return;
}
this.connectionId = connectionInfo.connectionId;
chrome.serial.onReceive.addListener(this.boundOnReceive);
chrome.serial.onReceiveError.addListener(this.boundOnReceiveError);
this.onConnect.dispatch();
};
SerialConnection.prototype.onReceive = function(receiveInfo) {
if (receiveInfo.connectionId !== this.connectionId) {
return;
}
this.lineBuffer += ab2str(receiveInfo.data);
var index;
while ((index = this.lineBuffer.indexOf('$')) >= 0) {
var line = this.lineBuffer.substr(0, index + 1);
this.onReadLine.dispatch(line);
this.lineBuffer = this.lineBuffer.substr(index + 1);
}
};
SerialConnection.prototype.onReceiveError = function(errorInfo) {
log('Error');
if (errorInfo.connectionId === this.connectionId) {
log('Error');
this.onError.dispatch(errorInfo.error);
log('Error');
}
log('Error');
};
SerialConnection.prototype.connect = function(path) {
serial.connect(path, this.onConnectComplete.bind(this))
};
SerialConnection.prototype.send = function(msg) {
if (this.connectionId < 0) {
throw 'Invalid connection';
}
serial.send(this.connectionId, str2ab(msg), function() {});
};
SerialConnection.prototype.disconnect = function() {
if (this.connectionId < 0) {
throw 'Invalid connection';
}
serial.disconnect(this.connectionId, function() {});
};
var connection = new SerialConnection();
connection.onConnect.addListener(function() {
log('connected to: ' + DEVICE_PATH);
);
connection.onReadLine.addListener(function(line) {
log('read line: ' + line);
});
connection.onError.addListener(function() {
log('Error: ');
});
connection.connect(DEVICE_PATH);
function log(msg) {
var buffer = document.querySelector('#buffer');
buffer.innerHTML += msg + '<br/>';
}
document.querySelector('button').addEventListener('click', function() {
connection.send(2);
});
Maybe I'm reading the code incorrectly, but at no point do you pass receiveTimeout into chrome.serial. The method signature is chrome.serial.connect(string path, ConnectionOptions options, function callback), where options is an optional parameter. You never pass anything into options. Fix that and let us know what happens.