Get Azure Cosmos Table values to HTML - javascript

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

Related

Conditional redirection depending on Current URL. through html

(1)
My example Current URL along with Parameters is ----
www.example.com?fname=John&femail=john123#example.com
(2)
Through html / JavaScript
I want to check Current URL Parameter whether it contains any data in
fname
(3a)
Next, If there is No URL Parameter present then Redirect to "www.example.com/error-page"
or
(3b)
If the parameter fname have some data (No need for any Validation of data) meaning the parameter fname is not empty then should Continue with the execution of Current Page.
I tried the following successfully :
<!doctype html>
<html>
<head>
<body>
<div>
<p id ="dd"></p>
</div>
<meta charset="UTF-8"/>
<script type="text/javascript">
var iid=document.getElementById("dd");
var getURL=window.location.href;
var theString = window.location.href;
var theWord = "fname";
var theWordExp = /fname/g;
if (theString.search(theWordExp) == -1) { window.location.href=
('www.example.com/error-page'); };
</script>
</body>
</head>
</html>
Explanation:
"I want to check Current URL Parameter whether it contains any data in fname"
The getQueryParam function is explained here
How to get "GET" request parameters in JavaScript?
basically it's almost the same as your approach using the location href to parse the params
"If there is No URL Parameter present then Redirect to" else continue, for this you'll only need to wrap it inside a div, if the conditional is false (found param) then it'll just not run the statement inside if block (the one that will redirect user to error page)
Note that you have many other option to implement, check with the compatibility of browser, behaviour of redirection can also be changed to replace the last history page so user cannot go back to the previous URL that throw the error using window.location.replace method
const getQueryParam = (name) => {
if (name = (new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)')).exec(location.search))
return decodeURIComponent(name[1]);
}
let fnameParam = getQueryParam("fname");
if (!fnameParam) {
window.location = "http://www.example.com/error-page";
};
<!doctype html>
<html>
<head>
<body>
<div>
<p id="dd"></p>
</div>
</body>
</head>
</html>

How to load data from external JSON API onclick (Cant use fetch)

I am trying to create an IE11 compatible webpage which will sit on a few users desktops, which will grab some data from a JSON API and display it.
The user will type in their individual API key before pressing a button, revealing the API data.
Could you please help where my code has gone wrong? The error message I get from the console is: "Unable to get property 'addEventListener' of undefined or null reference. " So it looks like it is not even making the call to the API.
<script>
var btn = document.getElementById("btn");
var apikey = document.getElementById("apikey").value
btn.addEventListener("click", function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://example.example?&apikey=' + document.getElementById("apikey").value);
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var ourData = JSON.parse(ourRequest.responseText);
document.getElementById("title").textContent = ourData.data[0]["name"];
}}}
);
</script>
.
<body>
Enter API key: <input type="text" id="apikey">
<button id="btn">Click me</button>
<p id="title"></p>
</body>
The API data which I am trying to just extract the name from, looks something like this:
{"data":[{"name":"This is the first name"},{"name":"This is the second name"}]}
It's likely that you're including the Javascript in the page before the HTML. As Javascript is executed as soon as the browser reaches it, it will be looking for the #btn element which will not have been rendered yet. There are two ways to fix this:
Move the Javascript to the bottom of the <body> tag, making it run after the HTML has been output to the page.
Wrap the Javascript in a DOMContentLoaded event, which will defer the script until the page has finished loading. An example is as follows:
window.addEventListener('DOMContentLoaded', function() {
var btn = document.getElementById('btn');
var apikey = document.getElementById("apikey").value;
[...]
});

Using basic jQuery append function, how would you put user-submitted text into it?

function createPost(){
$('#body').append("<p>Welcome to calmspace.</p>");
}
How would I utilize user input so the user can create a post with their own message? I am a newbie with jQuery so if this is a stupid question please forgive me. Possible duplicate but I couldn't find another post like this.
First things first - you should not have added '#' in front of body, it'd mean that the body element is of id 'body', assigning id to an element that is unique does not bear that much sense, instead you should just target the tag - $('body').
In order to provide some sort of message you first have to capture it, for instance using some sort of input. Here is a working demo.
$('#submit').click(function(){
createPost($('#text').val());
})
You read it as follows, grab element of id 'submit', assign it a click event, grab the value of input box of id 'text' and pass it to a function named create post which accepts a string parameter and then prints it in a <p> tag.
#Simion Benderschii a working example of a post which appends to the document or sends via ajax. Hope this helps
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title>JS Bin</title>
</head>
<body>
<div>
<h2>Enter your post here</h2>
<form>
<textarea id='user-input-post'></textarea>
<div>
<button id=user-post-button>Post</button>
</div>
</form>
</div>
<div>
<h2>Below are your posts</h2>
<ul id='user-post-display'>
</ul>
</div>
</body>
<script>
/*possible options can be
'display' - which shows the post in the UI in a unordered list
'ajax' - which send the post to the server via ajax
*/
var post_type = 'display';
//the id of the list where the post will be appended
var list_id = '#user-post-display';
//the id where the post will be entered
var post_id = '#user-input-post';
//the id of the button which triggers some action
var button_id = '#user-post-button';
//this gets the post from the textarea
var get_post = function() {
var post = $(post_id).val();
return encodeURIComponent(post);
};
//this appends the post to the list
var append_post = function() {
var post = get_post();
var html_string = '';
if (post) {
html_string = '<li>' + post + '</li>';
$(list_id).append(html_string);
}
};
//this sends the post via ajax and triggers callbacks
var send_post = function() {
var post = get_post();
var post_created_on = Date.now();
var url = 'dummy_url_for_posting';
$.ajax({
method: 'POST',
url: url,
data: { data: {
post: post,
post_created_on: post_created_on
}}
})
.done(function() {
window.alert('post success');
})
.fail(function() {
window.alert('post fail');
})
.always(function() {
window.alert('post triggered');
});
}
//main function which is the entry point
var main = function() {
$(button_id).on('click', function() {
event.preventDefault();
debugger;
if (post_type === 'display') {
append_post();
} else if (post_type === 'ajax') {
send_post();
}
});
};
//triggers the main function
main();
</script>
</html>
I am not exactly sure what you want to do from your question. In future questions you will find it helpful to provide more detail on exactly what you want to do with your application or function.
The basic idea here is to use a button or any action you can capture with jQuery (like pressing enter or checking $(element).on('click',... and then putting that info where you want using $(element).html(...) or .append(...).
Here is a fiddle I made with the rough idea. Try to use this fiddle tool a lot, and you can also post the link to what you have tried in future questions. Good luck :-)
JSFiddle example of submitting a post

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

Javascript - Getting a page title and meta description and using them as variables for a chrome extension

I have a script that gets the title from a tab and assigns it to a variable. However, I need to also get the meta desc and title properties for use in an input field.
I am not sure if I can achieve that with this:
chrome.tabs.getSelected(null, function(tab) {
var currentTitle = tab.title;
});
Then I need to get the Meta description, which I don't believe I can get from the tab data.
This is the HTML I am getting the description from:
<meta name="description" content="contentstuffya" />
This is the Javascript I am using to get it outside of the extension:
document.getElementsByName('description')[0].getAttribute('content');
How would I best do this given the data that I have?
The value of a <meta> tag can only be read through a content script. Here's an example:
var code = 'var meta = document.querySelector("meta[name=\'description\']");' +
'if (meta) meta = meta.getAttribute("content");' +
'({' +
' title: document.title,' +
' description: meta || ""' +
'});';
chrome.tabs.executeScript({
code: code
}, function(results) {
if (!results) {
// An error occurred at executing the script. You've probably not got
// the permission to execute a content script for the current tab
return;
}
var result = results[0];
// Now, do something with result.title and result.description
});
At the first line, I locate the <meta name="description"> element. At the second line, I read the value of its content attribute if the element is present.
The callback of chrome.tabs.executeScript receives the last expression's return value, so I've put an object literal (wrapped in parentheses) at the end of the code.
A better way to do it is using this.
function getMeta(metaName) {
const metas = document.getElementsByTagName('meta');
for (let i = 0; i < metas.length; i++) {
if (metas[i].getAttribute('name') === metaName) {
return metas[i].getAttribute('content');
}
}
return '';
}
console.log(getMeta('description'));
To get the title you can just use
console.log(document.title)
How do I get the information from a meta tag with JavaScript?

Categories

Resources