How to update html document using feather js? - javascript

I have a service that I call after every 5 secs to return data from postgres table, now I want this data to be displayed on html document
app.js
const stats=app.service('test_view');
// console.log(stats);
function getstats(){
stats.find().then(response=>{
console.log('data is ',response.data)});};
setInterval(function() {
getstats();
}, 5000);
// console.log(stats);
stats.html
<!DOCTYPE html>
<html>
<head>
<title>Stats</title>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div id='stats'>
</div>
</body>
</html>
Everything is running fine and I am getting results in console, I am using feather.js now I want these results to be displayed in div tag of html.Please help me in this regard.

You need to call the feathers service from the browser. You can do this a number of different ways (as a REST call, with the feathers client, etc.).
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/core-js/2.1.4/core.min.js"></script>
<script src="//unpkg.com/#feathersjs/client#4.0.0-pre.3/dist/feathers.js"></script>
<script src="//unpkg.com/axios/dist/axios.min.js"></script>
<script>
// #feathersjs/client is exposed as the `feathers` global.
const app = feathers();
app.configure(feathers.rest('http://localhost:3000').axios(axios));
app.service('test_view').find();
})
.then(data => {
// do something with data
});
</script>
</head>
<body></body>
</html>
A lot of this depends on what (if anything) you're using for your front-end implementation. This sets up a minimal feathersjs/client using axios for REST, with no authentication, and calls your service (on port 3000) and gets the payload.
To do this every 5 seconds is outside the scope of feathers and up to how you build your web app.

Here is a working example of how you could change the contents of that div when you get data back from your remote call.
// Simulate your remote call... ignore this part.
const stats = {}
stats.find = () => new Promise((resolve, reject) => resolve({
data: 'here is some data ' + new Date().toLocaleTimeString('en-US')
}));
// Div you want to change.
const resultsDiv = document.getElementById('stats');
// Get the data
function getstats () {
stats.find().then(response => {
console.log('data is ', response.data);
// Update the contents of the div with your data.
resultsDiv.innerHTML = response.data;
});
}
setInterval(function() {
getstats();
}, 1000);
<html>
<head>
<title>Stats</title>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div id='stats'>
</div>
</body>
</html>

Related

How can I fetch data from an API, process the data and render everything after the data was parsed?

My problem is that while fetching data from an API the website is already loaded, so for a second or so I see the default data in the elements and only after that the element data is updated.
I've already tried many ways like Async/Await and Promises and also events like jQuery.ready(), window.onload(), and the DOMContainerLoaded event on the fetch method but everytime, the page loads first.
In short, I want to (in order):
Get the data from an API (json)
Parse the data to an Object
Updated the elements on the page with the data
Render the whole page
This is what I have at the moment:
Player.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="/css/main.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="/public/js/classes.js" charset="utf-8"></script>
<script src="/public/js/player.js" charset="utf-8"></script>
</head>
<body>
<div class="container">
<img id="playerAvatar" class="avatar" alt="The avatar of the player">
<h2 id="nick"></h2>
<!-- More Stuff Later -->
</div>
</body>
</html>
player.js
window.addEventListener('DOMContentLoaded', async function(){
const player = await processPlayerData();
fillPlayerData(player);
});
async function processPlayerData(){
const user = new URLSearchParams(window.location.search).get('id');
const json = await requestData('/api/player/'+ user, {method: "GET"});
let player = new Player();
if("errors" in json)
player = null;
else
player.fillData(json);
return player;
}
async function requestData(dir, options) {
const response = await fetch(dir, options)
.then((response) => { return response.json(); });
return response;
}
function fillPlayerData(player){
if(player === null)
alert("The user does not exist!");
else{
document.getElementById('nick').innerHTML = "AlexMFV"; //player.nickname;
document.getElementById('playerAvatar').src = "https://media.gettyimages.com/photos/colorful-powder-explosion-in-all-directions-in-a-nice-composition-picture-id890147976?s=612x612"; //player.avatarUrl;
//Fill the elements with all the player data
//Get all player matches
}
return true;
}
And also on the server I have a method that is gathering the JSON from the API:
async function getPlayerData(req, res){
let value;
try{
const user = req.params.id;
value = await fetch(strPlayerData.replace('<usr>', user), packet).then((res) => { return res.json(); });
res.json(value);
}
catch(e){
error(res, e);
}
}
If there is something that you don't understand please tell me so that I can provide more information.
Edit: If you want to try it so that you can see what I mean, the project is available here: https://faceitstats.alexmfv.com/player.html?id=Alex

Firefox Storage Access API denies local storage after successful requestStorageAccess() call

I want to test the new Firefox Storage Access API to allow 1st party storage (cookie, local storage, indexeddb, ...) to an iframe of a different domain (but still under my control).
Parent Markup / code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Parent Domain</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.0/js.cookie.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jschannel/1.0.0-git-commit1-8c4f7eb/jschannel.min.js"></script>
</head>
<body>
<div>
Cookies: <ul class="cookie-data"></ul>
</div>
<iframe
id="rpc-gateway"
src="http://child.local:8080/iframe-firefox.html"
sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin"></iframe>
<script type="text/javascript">
var chan = Channel.build({
window: document.getElementById("rpc-gateway").contentWindow,
origin: "*",
scope: "testScope"
});
</script>
</body>
</html>
Child Iframe Markup / code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Child Domain</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.0/js.cookie.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jschannel/1.0.0-git-commit1-8c4f7eb/jschannel.min.js"></script>
</head>
<body>
<button onClick="onLoginClick()">Login</button>
<script type="text/javascript">
var chan = Channel.build({
window: window.parent,
origin: "*",
scope: "testScope"
});
let onLoginClick = function(trans, params) {
document.hasStorageAccess().then(hasAccess => {
if (!hasAccess) {
console.log("no access - requesting access");
return document.requestStorageAccess();
}
}).then(_ => {
document.hasStorageAccess().then(hasAccess => {
console.log("hasAccess:", hasAccess);
window.localStorage.setItem('foo', 'bar');
})
}).catch((err) => {
console.log("hasStorageAccess() failed", err);
});
};
</script>
</body>
</html>
When clicking on the "Login" button from the Child Iframe, the following log output is generated:
no access - requesting access # iframe-firefox.html:22:25
hasAccess: true # iframe-firefox.html:27:25
Request to access cookie or storage on “http://child.local:8080/iframe-firefox.html” was blocked because we are blocking all third-party storage access requests and content blocking is enabled. # iframe-firefox.html:28:24
The visible conclusion is:
The promise document.hasStorageAccess() resolves
The hasAccess parameter is initially 'false'
The promise of document.requestStorageAccess() is returned and resolves
The 2nd promise document.hasStorageAccess() resolves
The hasAccess parameter is now 'true'
nevertheless, simple storage access to local storage is not possible.
What do I do wrong?
More Info's:
Firefox Developer Edition Version 65.0b9
Content Blocking Setting:
This seems to be a bug in the version of Firefox you're using. I set up a test locally of what you have and in Firefox 69.0.1 (64 bit), I get no error and the value is stored to local storage. When I took the sandbox flag allow-storage-access-by-user-activation out of the parent iframe, the child failed to get permission for local storage, so that confirms that my setup was actually working properly. Here's what I did:
Created a Node.js/Express server for the parent:
const express = require('express');
const cors = require('cors');
const path = require('path');
const server = express();
server.use(cors());
server.use(express.static(path.resolve('./public')));
server.listen(8080, function() {
console.log('listening on *:8080');
});
Created a Node.js/Express server for the child (with different port to trigger same origin policy):
const express = require('express');
const cors = require('cors');
const path = require('path');
const server = express();
server.use(cors());
server.use(express.static(path.resolve('./public')));
server.listen(8081, function() {
console.log('listening on *:8081');
});
Created an index.html for the parent (pretty much the same as yours):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Parent Domain</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.0/js.cookie.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jschannel/1.0.0-git-commit1-8c4f7eb/jschannel.min.js"></script>
</head>
<body>
<div>
Cookies: <ul class="cookie-data"></ul>
</div>
<iframe
id="rpc-gateway"
src="http://127.0.0.1:8081/iframe-firefox.html"
sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin"></iframe>
<script type="text/javascript">
var chan = Channel.build({
window: document.getElementById("rpc-gateway").contentWindow,
origin: "*",
scope: "testScope"
});
// Added this to try out the JSChannel
chan.call({
method: "reverse",
params: "hello world!",
success: function(v) {
console.log(v);
}
});
</script>
</body>
</html>
And created iframe-firefox.html for the child:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Child Domain</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.0/js.cookie.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jschannel/1.0.0-git-commit1-8c4f7eb/jschannel.min.js"></script>
</head>
<body>
<button onClick="onLoginClick()">Login</button>
<script type="text/javascript">
var chan = Channel.build({
window: window.parent,
origin: "*",
scope: "testScope"
});
// Other end of the JSChannel call
chan.bind("reverse", function(trans, s) {
return s.split("").reverse().join("");
});
let onLoginClick = function(trans, params) {
document.hasStorageAccess().then(hasAccess => {
if (!hasAccess) {
console.log("no access - requesting access");
return document.requestStorageAccess();
}
}).then(_ => {
document.hasStorageAccess().then(hasAccess => {
console.log("hasAccess:", hasAccess);
window.localStorage.setItem('foo', 'bar');
})
}).catch((err) => {
console.log("hasStorageAccess() failed", err);
});
};
</script>
</body>
</html>
And everything worked as expected... So I'm feeling pretty sure that the issue is with the specific version of Firefox Developer Edition that you're using.
Also, here's a link to a zip of my setup if you want to give it a try on your end and see if this works differently than what you have: server.zip
Let me know if there's anything else I can do to help.

Difficulties running JavaScript (from .js file) in an Angular application

I am trying to incorporate a Javascript function (contained in app.js), which I am trying to run from the index.html of my Angular 2 application.
Initially I used a CLI program called Office Add-in generator to make a non-angular application, in which this JavaScript works.
However when using the Add-in generator in an Angular application the app.js file is not automatically generated. Manually copy pasting the app.js file and <script> link does not work either. I realise I have only provided a couple of files worth of code, let me know if I should edit more in, or provide a github link?
The error in chrome is net::ERR_ABORTED not defined with a 404 message. (relating to the app.js file)
~~~~HTML~~~~~
<head>
<link rel="stylesheet" href="https://appsforoffice.microsoft.com/fabric/1.0/fabric.css">
<link rel="stylesheet" href="https://appsforoffice.microsoft.com/fabric/1.0/fabric.components.css">
<meta charset="utf-8">
<title>Microsoft Graph Connect sample</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<script src="https://appsforoffice.microsoft.com/lib/1/hosted/Office.js" type="text/javascript"></script>
<script>
window.history.replaceState = function(){};
window.history.pushState = function(){};
</script>
</head>
<body>
<app-root></app-root>
<button onclick="setItemBody()">Paste to email</button>
<script type="text/javascript" src="node_modules/core-js/client/core.js"></script>
<script type="text/javascript" src="node_modules/jquery/dist/jquery.js"></script>
<script type="text/javascript" src="node_modules/office-ui-fabric-js/dist/js/fabric.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
~~~~~~~app.js~~~~~~~~
var item;
Office.initialize = function () {
item = Office.context.mailbox.item;
// Checks for the DOM to load using the jQuery ready function.
$(document).ready(function () {
// After the DOM is loaded, app-specific code can run.
// Set data in the body of the composed item.
// setItemBody();
});
}
// Get the body type of the composed item, and set data in
// in the appropriate data type in the item body.
function setItemBody() {
item.body.getTypeAsync(
function (result) {
if (result.status == Office.AsyncResultStatus.Failed){
write(result.error.message);
}
else {
// Successfully got the type of item body.
// Set data of the appropriate type in body.
if (result.value == Office.MailboxEnums.BodyType.Html) {
// Body is of HTML type.
// Specify HTML in the coercionType parameter
// of setSelectedDataAsync.
item.body.setSelectedDataAsync(
'<b>These are the times I am available:</b><br>Monday -- 8:30 to 9:00<br>Tuesday -- 1:00 to 5:00<br>Thursday -- 4:00 to 5:00<br>',
{ coercionType: Office.CoercionType.Html,
asyncContext: { var3: 1, var4: 2 } },
function (asyncResult) {
if (asyncResult.status ==
Office.AsyncResultStatus.Failed){
write(asyncResult.error.message);
}
else {
// Successfully set data in item body.
// Do whatever appropriate for your scenario,
// using the arguments var3 and var4 as applicable.
}
});
}
else {
// Body is of text type.
item.body.setSelectedDataAsync(
' Kindly note we now open 7 days a week.',
{ coercionType: Office.CoercionType.Text,
asyncContext: { var3: 1, var4: 2 } },
function (asyncResult) {
if (asyncResult.status ==
Office.AsyncResultStatus.Failed){
write(asyncResult.error.message);
}
else {
// Successfully set data in item body.
// Do whatever appropriate for your scenario,
// using the arguments var3 and var4 as applicable.
}
});
}
}
});
}
// Writes to a div with id='message' on the page.
function write(message){
document.getElementById('message').innerText += message;
}
Actually you should not just put your js files in index.html better add in .angular-cli.json file.. and about js not working in ng2+ project.. check out https://angular.io/guide/attribute-directives I think you must make wrapper. check this as well https://medium.com/#NetanelBasal/typescript-integrate-jquery-plugin-in-your-project-e28c6887d8dc

how to call one file input id into another file using javascript

im having 2 html files, in my first file i have declared a variable and i want to use the same variable in my second file...
my first file code is
<script type="text/javascript">
function topics(clicked_id)
{
var ids = clicked_id;
var myObject, fol;
myObject = new ActiveXObject("Scripting.FileSystemObject");
if(!myObject.FolderExists("D:/JavaScript/Work/Days/"+ids))
{
fol = myObject.CreateFolder("D:/JavaScript/Work/Days/"+ids);
}
load_page();
}
function load_page()
{
open("file:///D:/JavaScript/Work/Topics_Page.html");
}
</script>
i want to use "ids" variable in my second file...
Thanks;
If the HTML documents have the same origin you can use postMessage, MessageChannel, SharedWorker or storage event to communicate between different browsing contexts, see
How can I load a shared web worker with a user-script?
Can we refer to JavaScript variables across webpages in a browser session?
how to pass data from one html page to second in php?
You can use localStorage and storage event to use the same object variable, or define a local variable set to the value of localStorage at a different HTML documenta having the same domain.
<!DOCTYPE html>
<html>
<head>
<title>index</title>
</head>
<body>
otherPage.html
<h1>set id</h1>
<script>
let id;
let h1 = document.querySelector("h1");
h1.onclick = e => {
id = `${Math.E * Math.PI * Math.random()}`;
localStorage.setItem("id", id);
console.log(`id: ${id} at ${e.type}`);
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>other page</title>
<script>
let id = localStorage.getItem("id");
console.log(`id: ${id} at ${document.title}`);
onstorage = e => {
console.log(`id: ${localStorage.getItem("id")} at ${e.type}`);
id = localStorage.getItem("id");
console.log(id);
}
</script>
</head>
<body>
<h1>otherPage.html</h1>
</body>
</html>
plnkr https://plnkr.co/edit/m4RIdwgIl74Dk6YmGAgI?p=preview

Simple youtube javascript api 3 request not works

i've tried to write a simple youtube request to search video with youtube javascript api v3.
This is the source code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function showResponse(response) {
var responseString = JSON.stringify(response, '', 2);
document.getElementById('response').innerHTML += responseString;
}
// Called automatically when JavaScript client library is loaded.
function onClientLoad() {
gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
}
// Called automatically when YouTube API interface is loaded
function onYouTubeApiLoad() {
// This API key is intended for use only in this lesson.
gapi.client.setApiKey('API_KEY');
search();
}
function search() {
var request = gapi.client.youtube.search.list({
part: 'snippet',
q:'U2'
});
// Send the request to the API server,
// and invoke onSearchRepsonse() with the response.
request.execute(onSearchResponse);
}
// Called automatically with the response of the YouTube API request.
function onSearchResponse(response) {
showResponse(response);
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
</head>
<body>
<pre id="response"></pre>
</body>
</html>
When i load this page on google chrome (updated), nothing happens, the page remains blank.
I have request the API Key for browser apps (with referers) and copied in the method gapi.client.setApiKey.
Anyone can help me?
Thanks
Try this example here
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google AJAX Search API Sample</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
// How to search through a YouTube channel aka http://www.youtube.com/members
google.load('search', '1');
function OnLoad() {
// create a search control
var searchControl = new google.search.SearchControl();
// So the results are expanded by default
options = new google.search.SearcherOptions();
options.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN);
// Create a video searcher and add it to the control
searchControl.addSearcher(new google.search.VideoSearch(), options);
// Draw the control onto the page
searchControl.draw(document.getElementById("content"));
// Search
searchControl.execute("U2");
}
google.setOnLoadCallback(OnLoad);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="content">Loading...</div>
</body>
</html>
When you use <script src="https://apis.google.com/js/client.js?onload=onClientLoad" ..></script>
you have to upload the html file somewhere online or use XAMPP on your PC
To use html for searching YT videos, using Javascript on PC, as I know, we need to use other codings:
1- Use javascript code similar to this for API version 2.0. Except only the existence of API KEY v3.
2- Use the jQuery method "$.get(..)" for the purpose.
See:
http://play-videos.url.ph/v3/search-50-videos.html
For more details see (my post "JAVASCRIPT FOR SEARCHING VIDEOS"):
http://phanhung20.blogspot.com/2015_09_01_archive.html
var maxRes = 50;
function searchQ(){
query = document.getElementById('queryText').value;
email = 'https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=50'+
'&order=viewCount&q='+ query + '&key=****YOUR API3 KEY*****'+
'&callback=myPlan';
var oldsearchS = document.getElementById('searchS');
if(oldsearchS){
oldsearchS.parentNode.removeChild(oldsearchS);
}
var s = document.createElement('script');
s.setAttribute('src', email);
s.setAttribute('id','searchS');
s.setAttribute('type','text/javascript');
document.getElementsByTagName('head')[0].appendChild(s);
}
function myPlan(response){
for (var i=0; i<maxRes;i++){
var videoID=response.items[i].id.videoId;
if(typeof videoID != 'undefined'){
var title=response.items[i].snippet.title;
var links = '<br><img src="http://img.youtube.com/vi/'+ videoID +
'/default.jpg" width="80" height="60">'+
'<br>'+(i+1)+ '. <a href="#" onclick="playVid(\''+ videoID +
'\');return false;">'+ title + '</a><br>';
document.getElementById('list1a').innerHTML += links ;
}
}
}
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body>
<input type="text" value="abba" id="queryText" size="80">
<button type="button" onclick="searchQ()">Search 50 videos</button>
<br><br>
<div id='list1a' style="width:750px;height:300px;overflow:auto;
text-align:left;background-color:#eee;line-height:150%;padding:10px">
</div>
I used the original code that Tom posted, It gave me 403 access permission error. When I went back to my api console & checked my api access time, it was expired. So I recreated the access time for the api. It regenerated new time. And the code worked fine with results.
Simply i must make request from a web server.
Thanks all for your reply

Categories

Resources