trigger function on separate window using intercom.js - javascript

When trying to use intercom.js I can print what my message is to the log in line 21 of the index file
intercom.on('notice', function (data) {
console.log(data);
$messages.append($('<p>').text(data.message));
document.title = '(' + $messages[0].childNodes.length + ') ' + title;
});
Is there any way when clicking it simply to trigger an alert on the other page.

In the read me file it gives you a basic code
// run this in multiple tabs!
var intercom = Intercom.getInstance();
intercom.on('notice', function(data) {
console.log(data.message);
});
intercom.emit('notice', {message: 'Hello, all windows!'});
Put the emit code on the page with the button, put the on code on the page where you want the alert to appear [of course change the console line to an alert.]
So making the alert happen would be:
Page 1 [Page with the alert]:
var intercom = Intercom.getInstance();
intercom.on('notice', function(data) {
alert(data.message);
});
Page 2 [Page with the button]:
function broadcast () {
var intercom = Intercom.getInstance();
intercom.emit('notice', {message: 'Hello, all windows!'});
}
document.getElementById("myButtonId").addEventListener("click", broadcast , false);

Related

How to add the value from an input box to an array and then output its contents?

How can I go about adding the value of an input box into an array and then display the contents of that array?
This is what I've come up with and I'm not sure why it's not working - the console.log doesn't post anything to the console, either.
var user = user;
if (!user) {
user = prompt('Please choose a username:');
if (!user) {
alert('Your name has been set to "Anonymous"');
} else {
alert('Your name has been set to "'+ user +'"');
}
}
var items = [];
function userArray() {
items.push(user);
return false;
console.log(items);
}
socket.on('onlineUsers', function (data) {
$('.dispUser').html(items);
});
The rest of the code in the file is below, just in case it helps... (changed the return statement, as per the first answer)
var user = user;
if (!user) {
user = prompt('Please choose a username:');
if (!user) {
alert('Your name has been set to "Anonymous"');
} else {
alert('Your name has been set to "'+ user +'"');
}
}
var items = [];
function userArray() {
items.push(users);
console.log(items);
return false;
}
socket.on('onlineUsers', function (data) {
$('.dispUser').html(items);
});
//Counts the number of users online
socket.on('count', function (data) {
$('.user-count').html(data);
});
//Receives messages and outputs it to the chat section
socket.on('message', function (data) {
$('.chat').append('<p><strong>' + data.user + '</strong>: ' + data.message + '</p>');
$('.chat').scrollTop($('.chat').height());
});
//SENDING OF THE MESSAGE
//Submit the form through HTTPS
$('form').submit(function (e) {
e.preventDefault();
// Retrieve the message from the user
var message = $(e.target).find('input').val();
// Send the message to the server
socket.emit('message', {
user: user || 'Anonymous',
message: message
});
// Clears the message box after the message has been sent
e.target.reset();
$(e.target).find('input').focus();
});
Answer
Your implementation is fine, but you have a bug which is preventing it from working as you've described.
The call to console.log(items) does not print anything, because that line of code never runs.
When you return from a function, the subsequent lines of code will not be ran. You should return as the last line within your function, or wrap it in a conditional.
For example:
function userArray() {
items.push(user);
console.log(items);
return false;
}
How to debug
Learning the techniques to figure this issue out yourself is an invaluable tool. You can leverage a debugger, such as the Chrome Devtools, to add breakpoints to your code. These will allow you to stop execution on a particular line, view the value of variables, and step through the remaining lines of code.
Doing so would make it clearly visible that the line of code is never running.
Find more details here: https://developers.google.com/web/tools/chrome-devtools/javascript

Javascript - How to get script to run with Ajax requested data

Battlefield Page
In the image above, there is a page that has a battlefield with 20 users on it. I have written JavaScript to capture the data and store it in a MySQL db. The problem comes into the picture when I need to hit next to go to the next page and gather that data.
It fetches the next 20 users with an Ajax call. Obviously when this happens, the script can't log the new information because the page never loads on an Ajax call which means the script doesn't execute. Is there a way to force a page load when the Ajax link is clicked?
Here's the code:
grabData();
var nav = document.getElementsByClassName('nav')[0].getElementsByTagName('td')[2].getElementsByTagName('a')[0];
nav.addEventListener("click", function(){
grabData();
});
function grabData(){
var rows = document.getElementsByClassName('table_lines battlefield')[0].rows;
var sendData = '';
for(i=1; i < rows.length -1 ; i++){
var getSid = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[2].getElementsByTagName('a')[0].href;
var statsID = getSid.substr(getSid.indexOf("=") + 1); //Grabs ID out of stats link
var name = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[2].textContent.replace(/\,/g,"");
var tff = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[3].textContent.replace(/\,/g,"");
var rank = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[6].textContent.replace(/\,/g,"");
var alliance = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[1].textContent.trim();
var gold = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[5].textContent.replace(/\,/g,"");
if(alliance == ''){
alliance = 'None';
}
if(gold == '??? Gold'){
gold = 0;
}else{
gold = gold.replace(/[^\/\d]/g,'');
}
sendData += statsID + "=" + name + "=" + tff + "=" + rank + "=" + alliance + "=" + gold + "#";
}
$.ajax({
// you can use post and get:
type: "POST",
// your url
url: "url",
// your arguments
data: {sendData : sendData},
// callback for a server message:
success: function( msg ){
//alert(msg);
},
// callback for a server error message or a ajax error
error: function( msg )
{
alert( "Data was not saved: " + msg );
}
});
}
So as stated, this grabs the info and sends to the php file on the backend. So when I hit next on the battlefield page, I need to be able to execute this script again.
UPDATE : Problem Solved. I was able to do this by drilling down in the DOM tree until I hit the "next" anchor tag. I simply added an event listener for whenever it was clicked and had it re execute the JavaScript.
Yes, you can force a page load thus:
window.location.reload(true);
However, what the point of AJAX is to not reload the page, so often you must write javascript code that duplicates the server-side code that builds your page initially.
However, if the page-load-code-under-discussion runs in javascript on page load, then you can turn it into a function and re-call that function in the AJAX success function.
Reference:
How can I refresh a page with jQuery?

Call SignalR Javascript function from modal popup

My DiaryHub.vb has the following:
Imports Microsoft.AspNet.SignalR
Imports Microsoft.AspNet.SignalR.Hubs
Namespace UIS
<HubName("DiaryHub")>
Public Class DiaryHub
Inherits Hub
Public Sub PostDiaryHeadline()
' Call the addNewMessageToPage method to update clients.
Clients.All.addNewDiaryHeadlineToPage()
End Sub
End Class
End Namespace
My Home/Index window has the following code to initiate/configure SignalR.
$(function () {
// Save the reference to the SignalR hub
var dHub = $.connection.DiaryHub;
// Invoke the function to be called back from the server
// when changes are detected
// Create a function that the hub can call back to display new diary Headline entry.
dHub.client.addNewDiaryHeadlineToPage = function () {
// refresh the Headline Entries to the page.
outputHLDiaryEntries();
};
// Start the SignalR client-side listener
$.connection.hub.start().done(function () {
// Do here any initialization work you may need
outputHLDiaryEntries();
});
})
The code works and on launch the Headline diary entries are displayed.
I also have a button that opens a Kendo window as a modal with a form for adding new diary entries using this function:
function openAddWindow() {
var addWindow = $("#window").data("kendoWindow");
addWindow.refresh({
url: "Home/AddDiaryEntry/"
});
addWindow.open();
addWindow.center();
}
I then have the following Javascript in my AddDiaryEntry page:
function createDiaryEntry() {
var validFlag = true;
var errorMsg = "";
//Validate New Diary Entry
// removed for brevity...
if (validFlag) {
//data is valid
//get value of checkbox
var cbValue = ($("#addNew_dHeadline").is(':checked')) ? true : false;
//clear error area
$('#errorArea').html("");
var response = ''
$.ajax({
url: 'Home/SaveDiaryEntry',
type: 'POST',
data: {
dDate: $("#addNew_dDate").text(),
dCreatedBy: $("#addNew_dCreatedBy").text(),
dName: '#AppShort',
dTeam: teamValue.value(),
dType: typeValue.value(),
dRef: $("#addNew_dREF").val(),
dHeadline: cbValue,
dServer: multiSelect.value(),
dComment: editor.value()
},
success: function (result) {
response = result;
alert(response);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
response = "err--" + XMLHttpRequest.status + " -- " + XMLHttpRequest.statusText + " -- " + errorThrown;
alert(response);
}
});
//close window
var addWindow = $("#window").data("kendoWindow");
addWindow.close();
//if headline entry call SignalR post function to refresh diary entries
if (cbValue) {
// reference to the SignalR hub
var dHub = $.connection.DiaryHub;
// function to update all clients
dHub.client.PostDiaryHeadline(); //THIS IS A FUNCTION IN DiaryHub.vb
}
} else {
//error in data
var out = '<ul class="error">' + errorMsg + '</ul>';
// display errors
$('#errorArea').html(out);
}
}
The code works fine - validates the data, saves data to database. The issue I'm having is when I try to call dHub.client.PostDiaryHeadline() to invoke the SignalR function. I get the error: JavaScript runtime error: Object doesn't support property or method 'PostDiaryHeadline'
How do I call the function? Should I call the function before I close the modal window?
From what I can see your actually expecting a response rather than a server call.
adding server will fire a request.
if (cbValue) {
// reference to the SignalR hub
var dHub = $.connection.DiaryHub;
// function to update all clients
dHub.server.PostDiaryHeadline(); //THIS IS A FUNCTION IN DiaryHub.vb
}
Your already receiving the response here:
dHub.client.addNewDiaryHeadlineToPage = function () {
// refresh the Headline Entries to the page.
outputHLDiaryEntries();
};
//EDIT
There seems to be slight issues through out, so apart from the above(which needs fixing).
On the hub name (backend) replace with: <HubName("diaryHub")>
In your JS replace with: var dHub = $.connection.diaryHub;
Finally in your createDiaryEntry(); body should look like so:
$.connection.hub.start().done(function () {
// Do here any initialization work you may need
if (cbValue) {
// reference to the SignalR hub
var dHub = $.connection.diaryHub;
// function to update all clients
dHub.server.postDiaryHeadline(); //THIS IS A FUNCTION IN DiaryHub.vb
}
});
There are a few SignalR issues but that should get you on the right path.
Most SignalR issues stem from case sensitivity and structuring. All very common.
Should be the last issue, replace with: dHub.server.postDiaryHeadline();
lower case "p"

Code is giving error, "ReferenceError: CryptoJS is not defined" , while I have included required .js references, what's the reason?

Here is my code, I have included following .js files, onpage load it is giving error "ReferenceError: CryptoJS is not defined" why does it give that error when already js references are added. I am making a sharepoint-2013 app using office 365.
<script type="text/javascript" src="../Scripts/sha1.js"></script>
<script type="text/javascript" src="../Scripts/hmac-sha1.js"></script>
'use strict';
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
(function () {
// This code runs when the DOM is ready and creates a context object which is
// needed to use the SharePoint object model
$(document).ready(function ()
{
getUserName();
$("#button1").click(function()
{
paraupdate();
});
});
// This function prepares, loads, and then executes a SharePoint query to get
// the current users information
function paraupdate()
{
var str=""+$("#textbox1").val();
alert(""+str);
var message = str+"json539ff0f815ca697c681fe01d32ba52e3";
var secret = "<my private key>";
var crypto = CryptoJS.HmacSHA1(message, secret).toString();
alert("crypto answer is " + crypto);
var siteurl="http://pnrbuddy.com/api/station_by_code/code/"+str+"/format/json/pbapikey/539ff0f815ca697c681fe01d32ba52e3/pbapisign/"+crypto;
$.ajax({
url: siteurl,
type: "GET",
dataType: 'json',
success: function (data) {
alert("IN Success");
alert(""+data.station_by_code);
},
error: function (error) {
alert("IN Error");
alert(JSON.stringify(error));
}
});
}
function getUserName()
{
context.load(user);
context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}
// This function is executed if the above call is successful
// It replaces the contents of the 'message' element with the user name
function onGetUserNameSuccess()
{
$("#label1").html("Enter Station Code : ");
$("#button1").val("CLICK");
}
// This function is executed if the above call fails
function onGetUserNameFail(sender, args) {
alert('Failed to get user name. Error:' + args.get_message());
}
})();
include core-min.js before sha256.js
There are one of two forms for fixing this:
1: Manual Load, i have more success with this pattern:
$.getScript(scriptbase + "SP.Runtime.js",
function () {
$.getScript(scriptbase + "SP.js", execOperation);
}
);
Example:
$.getScript("~hostUrl/_layouts/15/SP.RequestExecutor.js", getListDataREST);
2: Script on Demand:
SP.SOD.executeFunc('sp.userprofiles.js', 'SP.ClientContext', loadUserData);
This SharepointExchange posting, gives the usual JSOM implementation for most AppParts: Jquery is not firing on Page load SharePoint 2013
Error solved I added online references instead,
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/hmac-sha1.js"></script>
Maybe is too late, but:
var CryptoJS = require('crypto-js');
var hash = CryptoJS.HmacSHA256("Message", "secret");
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
console.log(hashInBase64); // qnR8UCqJggD55PohusaBNviGoOJ67HC6Btry4qXLVZc=
Works fine in node.js.

Node/Javascript: Redirect After Verification Button

I'm using a framework called PartialJS that follows a MVC architecture to build a webApp that will verify a user's input and make a request to an API and render the API response.
I'm not sure how to redirect the user to the rendered page after verification and API call has finished. Where should the page redirect and API calls be made?
Here's a quick breakdown of what the user will see with 'bullet' marks denoting what happens in the backend:
User presented with a form and fills information
exports.onValidation() called via a serialized JSON to verify that
all fields completed accurately (triggered by a button), done without
a page refresh.
API call is made with user's information, will not return until response is received and parsed
Form rendered with decoded JSON response from external API
I have tried using this in the 'view.html' page but the page redirects before verification.
<buttononclick="window.location='http://www.CaliCoder.com/results';">Submit</button>
<script type="text/javascript">
$(document).ready(function() {
$('button').bind('click', function() {
$.post('/', $('#f').serialize(), function(d) {
var err = $('#error');
if (d instanceof Array) {
err.empty();
d.forEach(function(o) {
err.append('<div>' + o.error + '</div>');
});
err.show();
return;
};
$('#f').trigger('reset');
err.empty();
err.show().html('SUCCESS! Please wait while the request is being made')
});
});
});
</script>
Here's what happens in the 'controller.js' end of things.
function json_form() {
var self = this;
var error = self.validate(self.post, ['intersection', 'hours', 'minutes', 'phone'])
if (error.hasError()) {
self.json(error);
return;
}
// save to database
var db = self.database('forms');
db.insert(self.post);
self.json({ r: true });
}
function get_routes(hours, minutes, intersection) {
//The following code makes a call that returns an array with data to be rendered by another view controller.
var stops = this.module('cumtd').GetStopsBySearch('springfied busey');
}
Thanks for reading! Sorry for sounding confusing, I'm new to JS and Node programming. :(
You have problem in clide-side JavaScript, solution:
HTML:
<button>Submit</button>
JavaScript:
$(document).ready(function() {
$('button').bind('click', function() {
$.post('/', $('#f').serialize(), function(d) {
var err = $('#error');
if (d instanceof Array) {
err.empty();
d.forEach(function(o) {
err.append('<div>' + o.error + '</div>');
});
err.show();
return;
};
$('#f').trigger('reset');
err.empty();
err.show().html('SUCCESS! Please wait while the request is being made');
// HERE REDIRECT:
setTimeout(function() {
window.location.href = 'http://www.CaliCoder.com/results';
}, 3000);
});
});
});

Categories

Resources