PHP "PUSH" To Javascript - javascript

Right now we have a web application that is ran on a local network where the clients run everything in javascript. In order to make sure everything is in sync these clients currently utilize an AJAX request to the server by sending the last "syncId" that it has recieved. The server then responds with an array tree of commands to get this client up to date. This is executed every second and has yet to cause any issues with network bandwith or latency however we are installing a system in a bigger client next month that may push the limits of this method and I am wondering if it is feasible to have the server "PUSH" the sync events to the clients in real time.
srvResponse=httpGet("CDSSync.php?sessionKey="+sessionKey+"&lastUpdate="+lastUpdate);
if(srvResponse!=0){
syncEvents=srvResponse.split(";");
for(var i=0; i<syncEvents.length; i++){
syncItem=syncEvents[i].split(",");
window["syncFunction_"+syncItem[1]](syncItem[2]);
lastUpdate=syncItem[0];
}
}
The above is where my system checks for events to be synced where syncItem[0] is a autoIncrement ID, syncItem[1] is a code for the event being handled and syncItem[2] is a parameter for the function. the httpGet function being called although not in this code is just a function that fetches from the server and returns the response.

Take a look at www.firebase.com, you can set up a push service from javascript clients to all others in minutes. Try the simple tutorial first:
<!doctype html>
<html>
<head>
<script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
<link rel='stylesheet' type='text/css' href='/resources/tutorial/css/example.css'>
</head>
<body>
<div id='messagesDiv'></div>
<input type='text' id='nameInput' placeholder='Name'>
<input type='text' id='messageInput' placeholder='Message'>
<script>
var myDataRef = new Firebase('https://hbw30ob2a8y.firebaseio-demo.com/');
$('#messageInput').keypress(function (e) {
if (e.keyCode == 13) {
var name = $('#nameInput').val();
var text = $('#messageInput').val();
myDataRef.push({name: name, text: text});
$('#messageInput').val('');
}
});
myDataRef.on('child_added', function(snapshot) {
var message = snapshot.val();
displayChatMessage(message.name, message.text);
});
function displayChatMessage(name, text) {
$('<div/>').text(text).prepend($('<em/>').text(name+': ')).appendTo($('#messagesDiv'));
$('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight;
};
</script>
</body>
</html>

Related

Get Azure Cosmos Table values to HTML

My goal is to change a text in my Html to a value from Azure Cosmos DB Table. How can I do that?
This is what I tried so far:
I'm using Azure Cosmos DB with the Table API. In this DB I have created a Table MyTable. In this Table I have one example entity:
Example Entity -> MyColumn: MyValue || MyColumn2: MyValue2 || ...
PartitionKey: 0 || RowKey: 0 || Text: MyText
I want MyText to be in an HTML. For this I created a WebApplication in VS2019 with this .html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link href="MyJS.js" />
<script type="text/javascript" src="MyJS.js"></script>
</head>
<body>
<button onclick="MyFunc()">whaddup</button>
<p id="MyId">text</p>
</body>
</html>
And this .js:
function MyFunc() {
var azure = require('azure-storage');
var tableSvc = azure.createTableService('myAccountName', 'myPrimaryKey', 'myEndpoint');
var query = new azure.TableQuery()
.where('PartitionKey eq ?', '0');
tableSvc.queryEntities('MyTable', query, null, function (error, result, response) {
if (!error) {
for (var key in result.entries) {
var value = result.entries[key];
for (var colName in value) {
var colVal = value[colName];
if (colName != ".metadata") {
var x = document.getElementById("MyId");
x.innerHTML = colVal._;
console.log(colName + ": " + colVal._);
}
}
}
}
});
}
The Html is just a button and a text. When clicking the button the text should change via the javascript.
The first error I encountered with this was 'require' is not defined when clicking the button. To fix this I used Browserify.
Then the next problem was that my function could not be found. I fixed this by changing function MyFunc() {...} to window.MyFunc = function() {...}.
And I ran into the next problem. When clicking the button I got this error:
Access to XMLHttpRequest at
'https://myAccountName.table.cosmos.azure.com/MyTable?%24filter=PartitionKey...'
from origin 'null' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Well I tried to fix this. I've seen something about using a proxy so I changed:
var tableSvc = azure.createTableService('myAccountName', 'myPrimaryKey', 'myEndpoint');
to this:
var tableSvc = azure.createTableService('myAccountName', 'myPrimaryKey', 'https://cors-anywhere.herokuapp.com/' + 'myEndpoint');
And now I got to this error when clicking the button:
GET
https://cors-anywhere.herokuapp.com/https://myAccountName.table.cosmos.azure.com/MyTable?%24filter=PartitionKey...
401 (Unauthorized)
And now last but not least two error messages that might be important to mention:
When going on this URL:
https://myAccountName.table.cosmos.azure.com/MyTable?%24filter=PartitionKey...
I get to see this:
{"odata.error":{"code":"MediaTypeNotSupported","message":{"lang":"en-us","value":"None of the provided media types are supported\r\nActivityId: someActivityIdHere, documentdb-dotnet-sdk/2.4.0 Host/64-bit MicrosoftWindowsNT/6.2.9200.0\nRequestID:someRequestIDhere\n"}}}
When visiting this URL:
https://cors-anywhere.herokuapp.com/https://myAccountName.table.cosmos.azure.com/MyTable?%24filter=PartitionKey...
I get to see this:
Missing required request header. Must specify one of: origin,x-requested-with

Why did fetch() API failed to retrieve custom HIBP JSON data?

I am trying to use the Have I Been Pwned? API to retrieve a list of breaches for a given email account.
I retrieve this list using the fetch() API. In the browser it looks like there is a connection to the HIBP website but the expected breaches are not visible.
I think this is a JSON problem because the API returns results without a root tree (?) (e.g. [breaches:{"Name"... - only the {"Name"}), so I think I'm making a mistake at the iteration step in the JS file. Also, I'm not calling the 'retrieve' function in the HTML file correctly because the browser throws an error: 'Uncaught ReferenceError: retrieve is not defined', but this is a side-issue (fetch('https://haveibeenpwned.com/api/v2/breachedaccount/test#example.com') doesn't work either).
This is my first week working with JS, fetch(), and JSON, so I consulted a couple of sources before asking this question (but I still can't figure it out, after a couple of days):
How to Use the JavaScript Fetch API to Get Data
fetch API
API methods for HaveIBeenPwnd.com (unofficial)
Where is the actual problem?
The index.html file:
<!DOCTYPE html>
<html lang=en>
<head>
<title>test</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow">
</head>
<body id="top">
<header id="header">
<div class="content">
<h1 style="text-align: center">Put an email in this box</h1>
<input type="email" id="InputBox" value="" autocapitalize="off" spellcheck="false" />
<button type="submit" id="PwnedButton" onclick="retrieve">pwned?</button>
<ul id="results"></ul>
</div>
</header>
<script src="test.js"></script>
</body>
</html>
The test.js file (I know that JS is an interpreted language - so empty characters affect execution speed - but I made it more readable for this example):
function createNode(element) {
return document.createElement(element); // Create the type of element you pass in the parameters
}
function append(parent, el) {
return parent.appendChild(el); // Append the second parameter(element) to the first one
}
const account = document.getElementById('InputBox');
const PwnedButton = document.getElementById('PwnedButton');
const results = document.getElementById('results');
fetch('https://haveibeenpwned.com/api/v2/breachedaccount/' + account)
.then((resp) => resp.json()) // Transform the data into json
.then(function(retrieve) {
let breaches = retrieve.Name; // Get the results
return breaches.map(function(check) { // Map through the results and for each one run the code below
let span = createNode('span'); // Create the element we need (breach title)
span.innerHTML = `${breaches}`;
append(results, span);
})
})
.catch(function(error) {
console.log(JSON.stringify(error));
});
let breaches = retrieve.Name;
retrieve is not an object with a Name property.
It is an array containing multiple objects, each of which has a Name property.
You have to loop over it.
e.g.
retrieve.forEach( item => {
let breaches = retrieve.Name;
console.log(breaches);
});
breaches.map
… and the Name is a string, so you can't map it. You can only map an array (like the one you have in retrieve).
I have created working version of what are you possible going to implement, taking Name field from result. https://jsfiddle.net/vhnzm1fu/1/ Please notice:
return retrieve.forEach(function(check) {
let span = createNode('span');
span.innerHTML = `${check.Name}<br/>`;
append(results, span);
})

Node sends data back multiple times everytime a user adds new data

First of all, I would like to apologize for the horribly worded title; I have been trying to think of one for the past 20 minutes but I do not know a succinct way to describe the problem I am having. If anyone has a better suggestion, please let me know or edit the title if you are able to.
Background: In order to learn NodeJS, I am creating a chat server. When the user clicks the createRoomBtn, an event is created containing the name of the room the user just created, and sent to the socket.js module in app.js, app.js then appends the room to the array of rooms (these rooms are displayed as a list in the browser), and creates a broadcast event to all users including the active user.
Problem: Let's say there is an empty list, and user adds a new room, titled "NodeJS", this will display the room on the screen, and everything is fine and dandy. Now, if I was to add another room, Socket.io, for example, the browser renders the following result: Socket.io, NodeJS, NodeJS. If I was to add "Javascript", the result would be Javascript, Socket.io, NodeJS, Socket.io, Node.JS. Basically, the browser renders the list over and over again, and each time the list shrinks by one. I do not have the slightest idea of why this is happening. The weird thing is that if I press refresh, the browser renders the list correctly Javascript, Socket.io, NodeJS. What is going on?
socket.js:
module.exports = function(io, rooms) {
var chatrooms = io.of('/roomlist').on('connection', function(socket) { //io.of creates a namespace
console.log('Connection established on the server');
socket.emit('roomupdate', JSON.stringify(rooms));
socket.on('newroom', function(data) {
console.log(data);
rooms.push(data);
socket.broadcast.emit('roomupdate', JSON.stringify(rooms));
socket.emit('roomupdate', JSON.stringify(rooms));
})
})
var messages = io.of('/messages').on('connection', function(socket) {
console.log('Connected to the chatroom!');
socket.on('joinroom', function(data) {
socket.username = data.user;
socket.userpic = data.userPic;
socket.join(data.room);
})
socket.on('newMessage', function(data) {
socket.broadcast.to(data.room_number).emit('messagefeed', JSON.stringify(data));
})
})
}
chatrooms.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{{title}}</title>
<link rel="stylesheet" href="../css/chatrooms.css">
<script src="//code.jquery.com/jquery-1.11.0.min.js"> </script>
<script src="/socket.io/socket.io.js"> </script>
<script>
$(function() {
var host = '{{config.host}}';
var socket = io.connect(host + '/roomlist');
socket.on('connect', function() {
console.log('connection established');
})
socket.on('roomupdate', function(data) {
$('.roomlist').html('');
var procData = JSON.parse(data);
for (var i = 0; i < procData.length; i++) {
var str = '<a href="room/' + procData[i].room_number + '"><li>'
+ procData[i].room_name + '<li></a>';
$('.roomlist').prepend(str);
console.log(str);
}
})
$(document).on('click', '#createRoomBtn', function() {
var room_name = $('#newRoomText').val();
console.log(room_name);
if (room_name != '') {
var room_number = parseInt(Math.random() * 10000);
socket.emit('newroom', {room_name: room_name, room_number: room_number});
$('#newRoomText').val('');
}
})
})
</script>
</head>
<body>
<div class="cr-userbox">
<img src="{{user.profilePic}}" class="userPic">
<h3 class="username">{{user.fullName}}| Logout</h3>
</div>
<div class="cr-container">
<h1> ChatRooms</h1>
<div class="cr-newroom">
<input type="text" id="newRoomText" autocomplete="off">
<input type="submit" id="createRoomBtn" value=" Create Room">
</div>
<div class="cr-roomlist">
<ul class="roomlist">
</ul>
</div>
</div>
</body>
</html>
Please let me know if more information/modules are required, and I will be happy to provide them.
Update1: As correctly suggested by alex-rokabilis, I have changed $('.roomlist').html() = '' to $('.roomlist').html(''), however, the problem continues to persist.
I'm not sure if this is the cause of your problem or not but you're getting nested list eliments because you have two opening <li> tags in your socket.on ('roomupdate') function
I believe the problem is how you render your rooms in the html part, not how socket.io sends the data.
You use $('.roomlist').html=''; but this is not doing anything! .html is a function in jquery so the right thing to do is $('.roomlist').html('');.
So basically you didn't erase the previous rooms but instead you only add more duplicates. Also something i noticed that is not part of your question, in your nodejs code you use: socket.broadcast.emit('roomupdate', JSON.stringify(rooms));
socket.emit('roomupdate', JSON.stringify(rooms));
if you want to broadcast something to all connected clients there is a function for it and also there is no need to stringify your data, socketio do this internally for you! So you could use something like this:
io.emit('roomupdate',rooms);

tokbox-opentok passed to one side only

I am using tokbox trial for video chatting on my website. But the problem i am facing is that ::: User 1 can see and hear User 2 clearly. User 2 can see User 1 clearly, but user 2 couldnt here user 1. And code i am using
<html>
<head>
<title>Monkvyasa | Test</title>
<script src='http://static.opentok.com/webrtc/v2.2/js/opentok.min.js'></script>
<script type="text/javascript">
// Initialize API key, session, and token...
// Think of a session as a room, and a token as the key to get in to the room
// Sessions and tokens are generated on your server and passed down to the client
var apiKey = "xxxxxxx";
var API_KEY=apiKey;
var sessionId = "2_MX40NTAyMDgxMn5-xxxxxxxxxxxxxxxxxxxxHBXZEZoWHN-fg";
var token = "T1==cGFydG5lcl9pZD00NTAyMDgxMiZzaWc9ZDNiYjYyZGE2NTBkYmUzMTUyNGNjNDZjYzAzY2NjZWRhZGY3NTEyZjpyb2xlPW1vZGVyYXRvciZzZXNzaW9uX2lkPTJfTVg0xxxxxxxxxxxxxxxxxxxxxxxxBNM1JsYlRCUFdXWkhSSEJYWkVab1dITi1mZyZjcmVhdGVfdGltZT0xNDEzMjAwMjIxJm5vbmNlPTAuMTk1MzEwNTU0MzY1MjEwNSZleHBpcmVfdGltZT0xNDEzMjg0MzY5";
// Initialize session, set up event listeners, and connect
var session;
var connectionCount = 0;
function connect() {
session = TB.initSession(sessionId);
session.addEventListener("sessionConnected", sessionConnectHandler);
session.addEventListener('streamCreated', function(event){
e=event;
console.log(e);
for (var i = 0; i < event.streams.length; i++) {
streams = event.streams;
// Make sure we don't subscribe to ourself
alert("new user connected :)");
if (streams[i].connection.connectionId == session.connection.connectionId) {
return;
}
// Create the div to put the subscriber element in to
var div = document.createElement('div');
div.setAttribute('id', 'stream' + streams[i].streamId);
document.body.appendChild(div);
session.subscribe(streams[i], div.id);
}
});
session.connect(API_KEY, token);
}
function sessionConnectHandler(event) {
var div = document.createElement('div');
div.setAttribute('id', 'publisher');
var publisherContainer = document.getElementById('publisherContainer');
// This example assumes that a publisherContainer div exists
publisherContainer.appendChild(div);
var publisherProperties = {width: 500, height:450};
publisher = TB.initPublisher(API_KEY, 'publisher', publisherProperties);
session.publish(publisher);
}
function disconnect() {
session.disconnect();
}
connect();
</script>
</head>
<body>
<h1>Monkvysa videofeed test!</h1>
<input style="display:block" type="button" id="disconnectBtn" value="Disconnect" onClick="disconnect()">
<table>
<tr>
<td> <div id="publisherContainer"></div></td> <td><div id="myPublisherDiv"></div></td>
</tr>
</table>
</body>
</html>
Thanks in advance
The code looks mostly correct, except you're using an older form of the 'streamCreated' event handler. In the latest version of the API, you no longer need to iterate through the event.streams array, you actually get one invocation of the event handler per stream.
In order to further dig into the problem, would you be able to add a link to a gist containing all the console logs? To make sure the logs are being outputted, you can call OT.setLogLevel(OT.DEBUG); at the beginning of the script.
Lastly, the newer API is greatly simplified and you could save yourself the effort of DOM element creation and iteration. What you have implemented is basically identical to our Hello World sample applications, which you can find in any of our server SDKs, for example here: https://github.com/opentok/opentok-node/blob/61fb4db35334cd30248362e9b10c0bbf5476c802/sample/HelloWorld/public/js/helloworld.js

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