Output html element content in another innerHTML js - javascript

I want to create a dynamic URL. The domain part should remain the same. For example: In this URL "https://www.google.com/search?", I want to append content fetched from another website.
I use this js to fetch and store result to Html element "KK1"
<script>
'use strict';
(async () => {
let response = await fetch('https://api.com/values/1');
let text = await response.text(); // read response body as text
document.getElementById("KK1").innerHTML = (text.slice(0, 80) );
})()
</script>
Assuming the response received from fetch is amoeba1, I want to generate a URL like "https://www.google.com/search?amoeba1"
My code
<!DOCTYPE html>
<html>
<head><script>
'use strict';
(async () => {
let response = await fetch('https://api.exchangeratesapi.io/latest?symbols=USD,GBP');
let text = await response.text(); // read response body as text
document.getElementById("KK1").innerHTML = (text.slice(0, 80) );
})()
</script>
<title>My title Dowmloder.rar</title>
</head>
<body>
<h2>My First Web Page</h2>
<p>My First Paragraph.</p>
Generate clickable URL from parameters.
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "https://www.google.com/search?"+ "I ADD WHAT HERE TO??";
</script>
BELOW IS THE STRING I WANT TO APPEND.
<p id="KK1"></p>
</body>
</html>
How do I append the fetched string? The string is already in
<p id="KK1"></p>
Looking Forward to getting help.

You are looking for anchor tag & you want to add dynamic href:
<!DOCTYPE html>
<html>
<head><script>
'use strict';
var res = "";
(async () => {
let response = await fetch('https://api.exchangeratesapi.io/latest?symbols=USD,GBP');
let text = await response.text(); // read response body as text
document.getElementById("KK1").innerHTML = (text.slice(0, 80) );
document.getElementById("demo").innerHTML = "https://www.google.com/search?"+ text;
document.getElementById("demo").href = "https://www.google.com/search?"+ encodeURI(text);
})()
</script>
<title>My title Dowmloder.rar</title>
</head>
<body>
<h2>My First Web Page</h2>
<p>My First Paragraph.</p>
Generate clickable URL from parameters.
<a id="demo"></a><br>
BELOW IS THE STRING I WANT TO APPEND.
<p id="KK1"></p>
</body>
</html>

document.getElementById("demo").innerHTML = "https://www.google.com/search?" + document.getElementById("KK1").innerHTML

Maybe you can modify your script to store in a variable the text result from your API call then with template literals, using ${} you can build your new string for demo element.
Like the following
const resultText = text.slice(0, 80);
document.getElementById("KK1").innerHTML = resultText;
document.getElementById("demo").innerHTML = `https://www.google.com/search?${resultText}`;
Or there are other ways to concatenate a string like:
'https://www.google.com/search?' + resultText
Read further here: Template literals (Template strings)
Update:
So you need to merge those two <script> tags what you have.
I guess this will do that job for you:
'use strict';
(async () => {
let response = await fetch('https://api.exchangeratesapi.io/latest?symbols=USD,GBP');
let text = await response.text(); // read response body as text
// essential modified part:
const resultText = text.slice(0, 80);
document.getElementById("KK1").innerHTML = resultText;
document.getElementById("demo").innerHTML = `https://www.google.com/search?${resultText}`;
})();
And don't forget to remove this one:
<script>
document.getElementById("demo").innerHTML = "https://www.google.com/search?"+ "I ADD WHAT HERE TO??";
</script>
I hope that helps!

Related

calling the next javascript via eval, remove the span tag created by the initial JS file

I have a html file and 2 JavaScript files: mainscript.js and script1.js. I inject the script1.js inside the mainscript.js. However, what happens is that by calling script1.js, the htmltags created by mainscript.js got removed. Any idea why this happens?
html code:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Linear Call</title>
</head>
<body>
<div id="main"><p>hi</p></div>
<script src="js/recursion_linear/MainScript.js">
</script>
</body>
</html>
mainscript.js:
const loadScript = async(url) => {
const response = await fetch(url)
const script = await response.text()
eval(script)
}
var s = document.createElement("span");
document.write("<br>");
s.innerText="This is main script";
s.id="mainscript";
document.body.append(s);
const scriptUrl_1 = "js/recursion_linear/Script1.js"
loadScript(scriptUrl_1)
script1.js:
document.write("<br>");
var s = document.createElement("span");
s.innerText="This is Script1";
s.id="script1";
document.body.append(s);
The output is
This is Script1
While the expected one is
This is main script
This is Script1

Check if url is working and if so do something

I found the following solution Checking if a URL is broken in Javascript
In the answer it says to use
checkLink = async url => (await fetch(url)).ok
to check if a url is available.
So let's assume I would like to display a message in case a url is working so I wrote:
let url = 'https://www.example.com/index.html';
if(checkLink = async url => (await fetch(url)).ok) {alert ("Hello world!");};
Unfortunately the above code always shows the alert message no matter if the url is available or not.
How can I use this code to test if a url is valid.
With the function definition you gave
checkLink = async url => (await fetch(url)).ok
you would typically use this as follows.
async function doStuff() {
let url = 'https://www.example.com/index.html';
let doesLinkWork = await checkLink(url);
if (doesLinkWork) {
alert("it works");
} else {
alert("it doesn't work");
}
}
and then call doStuff from the console or from somewhere else in your code. (Obviously that function name is just an example - you should call it something more appropriate to what you actually want it to do!)
If you are looking to use an input field or something of the sorts, you can use checkValidity().
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/checkValidity
<html>
<body>
<script>
function validation() {
const inp = document.getElementById("url");
const p = document.getElementById("text");
if(!inp.checkValidity()){
p.innerText = inp.validationMessage;
}
}
</script>
<form>
<input id="url" type="url" placeholder="URL Here">
<input type="submit" value="Submit" onclick="validation()">
</form>
<p id="text"></p>
</body>
</html>

JSON data not printing but prints on click (Uncaught TypeError: Cannot read property '1' of null)

I'm trying to print one of my data strings in HTML paragraph to test if the data is working. However, when I try and getElementById I get the error above. Although when I use a button to call the function I have no issues in printing the data. I think this has something to do with the order the data is read in, but I'm not quite sure. The code I have used is as follows:
<html>
<head>
<title>Untitled</title>
</head>
<body>
<p id="demo"> </p>
<script type="text/javascript">
//Stores data
var Data = null;
fetch('fetch.php')
.then(data => data.json())
.then(data => {
//Set data
Data = data;
console.log(Data);
});
document.getElementById("demo").innerHTML = Data[1].name;
function myFunction() {document.getElementById("demo").innerHTML = Data[1].name;}
</script>
<button onclick="myFunction()">Click me</button>
</body>
</html>
The problem is that fetch performs its tasks asynchronously and you are trying to access Data before its value is available.
Please try the following code.
I recommend you to read more about JS Promises and asynchronous code execution. However, if you have any doubt, please let me know.
<html>
<head>
<title>Untitled</title>
</head>
<body>
<p id='demo'> </p>
<script type="text/javascript">
let Data = null;
let myFunction = function () {
console.log('DATA IS NOT READY YET.');
};
fetch('fetch.php')
.then(data => data.json())
.then(data => {
myFunction = function () {
document.getElementById('demo').innerHTML = data[1].name;
};
});
</script>
<button onclick="myFunction()">Click me</button>
</body>
</html>

Tensorflow.js: cannot return a promise inside of tidy

Load below html file, wait for the first <textarea> to fill up, then click on Check Memory button. tf.tidy(main) function is supposed to clean all tensors instead its throwing an error in the console. The error is because of async\await. In my actual code i cannot remove async\await. Below is sample code to reproduce the issue.
Please help. Thanks!
<html>
<head>
<title>Split data as Training/Test</title>
<script src="https://cdn.jsdelivr.net/npm/#tensorflow/tfjs#2.0.0/dist/tf.min.js"></script>
</head>
<body onload="tf.tidy(main)">
<p>Total memory consumed:</p>
<textarea rows="10" cols="50" id="memory-before"></textarea>
<br><br>
<button onclick="showMemory()">Check Memory</button>
<br><br>
<textarea rows="10" cols="50" id="memory-after"></textarea>
<script>
/**
* Reading Data form CSV and splitting it into Training and Testing dataset.
* Program to split dataset in a csv file using TensorFlow tf.split
*/
async function main() {
// Import data from a CSV file.
const houseSalesDataset = tf.data.csv("http://127.0.0.1:8080/dataset/kc_house_data.csv");
// Extract x and y values to plot.
let pointsDataset = houseSalesDataset.map(record => ({
x: record.sqft_living,
y: record.price
}));
let pointsArray = await pointsDataset.toArray();
// Extract Features (inputs) and store it in a tensor.
let featureValues = pointsArray.map(point => point.x);
let featureTensor = tf.tensor2d(featureValues, [featureValues.length, 1]);
// Extract Labels (output) and store it in a tensor.
let labelValues = pointsArray.map(points => points.y);
let labelTensor = tf.tensor2d(labelValues, [labelValues.length, 1]);
document.getElementById('memory-before').innerHTML = JSON.stringify(tf.memory(), null, '\t');
}
function showMemory() {
document.getElementById('memory-after').innerHTML = JSON.stringify(tf.memory(), null, '\t');
}
</script>
</body>
</html>
Output:
Update:
Moved the tidy function invocation from onload to inside <script> tag as shown below but tidy is still not cleaning the memory.
tf.tidy(() => { main() });
i think the solution would be
const handelOnloadevent = async()=>{
tf.tidy(await main());
}
<body onload="handelOnloadevent"></body>
if tf.tidy doesn't accept the promise then just resolve the promise before passing it to tf.tidy

Generate a clickable URI that contains starting url + document.title + another string

I would like to generate a clickable URL that contains a starting URL string + document.title + another string + response.text. The link text should be "click here"
This is my code
<!DOCTYPE html>
<html>
<head>
<script>
'use strict';
var res = "";
(async () => {
let response = await fetch('https://httpbin.org/encoding/utf8');
let text = await response.text(); // read response body as text
document.getElementById("KK1").innerHTML = (text.slice(0, 10));
// I want to generate a clickable uri that contains starting url+document.title+another string+response.text. The link text should be "click here"
document.getElementById("demo").innerHTML = 'Click Here';
})()
</script>
<title>My File Dowmloder.rar</title>
</head>
<body>
<h2>My First Web Page</h2>
<p>My First Paragraph.</p> Generate clickable URL from parameters. <a id="demo"></a><br>
<p id="KK1"></p>
</body>
</html>
When I run this code the URL generated only contains the starting URL string, i.e. "https://www.google.com/search?". But I want the full URL to contain starting URL + document.title + another string + response.text.
Starting URL: https://www.google.com/search?
document.title: The page title
Another string: Any string
response.text: The string received from fetch
Looking forward for your help. Thanks all.
I'm not exactly sure what you are trying to do but this gets stuff and makes a link.
fetch('https://httpbin.org/encoding/utf8')
.then((response) => {
return response.text();
})
.then((text) => {
document.getElementById("KK1").innerHTML = text.slice(0, 10);
document.getElementById("demo").href = `https://www.google.com/search?${document.title}another string${text}`;
});
<html>
<head>
<title>My File Dowmloder.rar</title>
</head>
<body>
<h2>My First Web Page</h2>
<p>My First Paragraph.</p>
Generate clickable URL from parameters.
<a id="demo">Click Here</a><br>
<p id="KK1"></p>
</body>
</html>

Categories

Resources