Extract data from JSON in URL (real-time) - javascript

I am a green hand in building websites. The Hong Kong government recently released real-time open data on vacant parking spaces. I would like to display vacant spaces in a parking lot on my Weebly website. Could anyone help me with this by using the embed code? Thanks a lot!
For example, the vacancy of the car park is "12" now, I want to display "12" on my Weebly page.
Open data website provided by the government: https://sps-opendata.pilotsmartke.gov.hk/rest/getCarparkVacancy?carparkId=10
photo
This is my try, but it shows all data, how can I achieve the data for "vacancy" only.
<!DOCTYPE html>
<html>
<body>
<p id="demo">Fetch a file to change this text.</p>
<script>
let file = "https://sps-opendata.pilotsmartke.gov.hk/rest/getCarparkVacancy?carparkId=10"
fetch (file)
.then(x => x.text())
.then(y => document.getElementById("demo").innerHTML = y);
</script>
</body>
</html>

I have successfully written it myself. Thank you for all the guidance, and I will put my code here for others' reference.
<!DOCTYPE html>
<html>
<body>
<p id="demo">Fetch a file to change this text.</p>
<script>
let file = "https://sps-opendata.pilotsmartke.gov.hk/rest/getCarparkVacancy?carparkId=10"
fetch (file)
.then(x => x.json())
.then(y => document.getElementById("demo").innerHTML = y.results.privateCar.vacancy);
</script>
</body>
</html>

`
// function that pulls the data from the api and displays it on the html page
function search() {
const url = https://sps-opendata.pilotsmartke.gov.hk/rest/getCarparkVacancy?carparkId=10
fetch(url)
.then (response => response.json())
.then (data => {
vacancy = data.results.privateCar.vacancy
document.getElementById("htmlIdOfWhereIWantThisToDisplay").textContent = vacancy
})
}
// call the function
search()`

Related

Asp.net Project - Javascript button is clickable but not carrying out the function

I've been trying to integrate an api into a project that I have been working on with some friends but I'm having difficulty with getting the "ok" button to actually execute the function. It's supposed to allow you to upload a photo, click ok, and then it returns data about the plant. The "choose files button works, but the ok button doesn't.
Since the API sample was already created I tested it in a separate solution and was able to get it to work which leads me to believe that I've made a mistake in the code somewhere else or maybe there's something blocking the program from talking to API's web address. But for some reason it doesn't work within the project that I'm trying to integrate it into. (ASP.NET razor page).
I've also tried making a new button and moving the javascript tag into the header and other spots but that didn't work either, and I've run out of ideas to try. I have omitted the api key itself below for the sake of privacy. I'd really appreciate any help on the subject!
#{
ViewData["Title"] = "Identify a Plant";
}
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<form>
<input type="file" multiple />
<!--<button type="button">OK</button> -->
<button type="button">OK</button>
</form>
<script type="text/javascript">
document.querySelector('button').onclick = function sendIdentification() {
const files = [...document.querySelector('input[type=file]').files];
const promises = files.map((file) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (event) => {
const res = event.target.result;
console.log(res);
resolve(res);
}
reader.readAsDataURL(file)
})
})
Promise.all(promises).then((base64files) => {
console.log(base64files)
const data = {
api_key: "Die8ewFGvpw5JrRTuOEjgGR10uL--",
images: base64files,
modifiers: ["crops_fast", "similar_images"],
plant_language: "en",
plant_details: ["common_names",
"url",
"name_authority",
"wiki_description",
"taxonomy",
"synonyms"]
};
fetch('https://api.plant.id/v2/identify', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
})
};
</script>
</body>
</html>
I think you are better off to give the button a "ID" and you don't.
and I never really did like this idea of "selecting" some button and then hoping we can attached a click event to that button. So, I always preferred that you have a button. You place a button. You specify a click event for that button. You have to really struggle to figure out which button that selector going to pick up - which one does it like?
And then when you click on that button, the code or function runs. It just a lot easier to follow.
So, your button thus is this:
<form id="form1" runat="server">
<div>
<br />
<input id="myfiles" type="file" multiple="multiple" />
<!--<button type="button">OK</button> -->
<button id="MyButton" type="button" onclick="sendIdentification()" >OK</button>
</div>
</form>
<script type="text/javascript">
function sendIdentification() {
alert('start');
const files = [...document.querySelector('input[type=file]').files];
etc.
The problem is that selector for the click event is subject to the order of the controls and things on the page - might not be picked up correct.
So, just drop in a button. State what that button supposed to do on some click event, and this should help here.
With the querySelector method you add the onClick event on a first button within the document. Since the _Layout.cshtml is rendered first, my first assumption is that you have a button in that view? What about giving an id to the button and adding the onClick event like this:
document.getElementById("myButton").onclick = function sendIdentification() {
//the code
};

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>

Thymeleaf - How to interact and reload Javascript?

Without page refresh, I am calling an ajax request that goes to the controller and brings a Thymeleaf fragment,
On button click, I request the controller using ajax to get the fragment. Every Time I click on the button same fragment gets called but with a different <p> tag innerHTML.
<div id="express" th:fragment="Display">
<p id="app">Include details about your goals</p>
</div>
For the first time, js works very well, split into an array and add span tag but the issue with the new content which is dynamically replaced.
The issue is on the javascript side when the new fragments with different innerHTML inside of the <p> tag come the Javascript did not work. I need to refresh the page to re-run the js which I don't want to refresh.
here is the js
let comp = document.getElementById("app").innerHTML;
let struct = comp.split(" ");
document.getElementById("app").innerHTML = struct.reduce((acc, word, index) => {
return `${acc} <span class="word">${word}</span>`;
}, "");
const handleClick = () => {
axios.post(url)
.then(response => {
console.log(response.data);
$("#express").replaceWith($recievedHTML);
})
.catch(error => {
console.log(error);
});
}
Let's say you have your HTML page, which has your JS file or you have added your JS inside <script> tag directly. Something like ...
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<script src="/path/lib/jquery/3.5.1/jquery.min-dc5e7f18c8d36ac1d3d4753a87c98d0a.js" type="text/javascript"></script>
<script src="/path/js/your_file.min-cf4fcae72d4468307341eac1012bb6d8.js" type="text/javascript"></script>
</head>
<body>
<div id="express" th:fragment="Display">
<p id="app">Include details about your goals</p>
</div>
</body>
</html>
Javascript for this page may look like ...
$(function() {
function my_load_function() {
// do your loading procedures here
// for example I just copied your inline code...
let comp = document.getElementById("app").innerHTML;
let struct = comp.split(" ");
document.getElementById("app").innerHTML = struct.reduce((acc, word, index) => {
return `${acc} <span class="word">${word}</span>`;
}, "");
}
function my_do_something_else_function() {
// dosomething else over here
}
const handleClick = () => {
axios.post(url)
.then(response => {
console.log(response.data);
// what is '$recievedHTML'? should it be response.data?;
// ayway, you said replacement works;
$("#express").replaceWith($recievedHTML);
// after this call any function again
my_load_function();
my_do_something_else_function();
})
.catch(error => {
console.log(error);
});
};
// call your loading function first time
my_load_function();
});
I have put my additional explanation in the comments of JS code. Please note, I just write it directly in SO and didn't even try to run, so there are maybe some typos.

How do I read the data from text file into a variable so I can change the color based on the value?

The goal of my project is to read a stream of constantly changing data from a text file into a html file and then changing the font color.
I have tried multiple ways of reading in a text file such as using an iframe and attempting to use the fetch command but was unable to successfully use these to complete my goal.
<body>
<script type="text/javascript">
function print() {
fetch("test.txt")
.then(function(response) { return response.text; })
.then(function(text) {
var num = parseInt(text);
if(num>250){
num=fontcolor("green")
}
else()
{
num=fontcolor("red")
}
});
}
setInterval(print, 1000); //run function print() every 1 second
</script>
<META HTTP-EQUIV="refresh" CONTENT="1">
</body>
The outcome should be an html file that when opened in a browser will display the number in the text file and change the color based on the number given.
You can not fetch text file in local machine for security reason.
You can refer this link for update security for
Disable same origin policy in Chrome
You can host your file to free host. I corrected your .then(response => response.text())
Corrected
<body>
<script type="text/javascript">
function print() {
fetch("test.txt")
.then(response => response.text())
.then(text => {
var num = parseInt(text);
if(num>250){
console.log(num);
document.body.style.backgroundColor = "green";
}
else
{
//num=fontcolor("red")
console.log(num);
document.body.style.backgroundColor = "blue";
}
})
}
setInterval(print, 1000); //run function print() every 1 second
</script>
<META HTTP-EQUIV="refresh" CONTENT="1">
</body>
http://viethien.000webhostapp.com/fetchfile.html

Load, manipulate and save text file with javascript?

I've got a text file and want to do some find and replace operations to it inside the browser. Unfortunately my coding experience is just really elementary and complete tutorials about building web apps are far too much input at the moment.
Basically I want to upload the file into the browser, then let javascript do the find-and-replace-thing and finally want to download the changed file again.
I've already read about the HTML5 File API and was actually able to load the text file into the browser. But that is where I'm getting lost. In order to split problems up into smaller ones I thought a good next step would be to download the uploaded file again and finally learn how to put the find-and-replace action in between. But I really don't know how to go further and would appreciate any help.
Thanks so far. Benny
document.getElementById('input-file')
.addEventListener('change', getFile)
function getFile(event) {
const input = event.target
if ('files' in input && input.files.length > 0) {
placeFileContent(
document.getElementById('content-target'),
input.files[0])
}
}
function placeFileContent(target, file) {
readFileContent(file).then(content => {
target.value = content
}).catch(error => console.log(error))
}
function readFileContent(file) {
const reader = new FileReader()
return new Promise((resolve, reject) => {
reader.onload = event => resolve(event.target.result)
reader.onerror = error => reject(error)
reader.readAsText(file, "windows-1252")
})
}
<html>
<head>
<meta content="text/html; charset=ANSI" http-equiv="content-type">
<title>Text file manipulator</title>
</head>
<body>
<h1>Text file manipulator</h1>
<p>
<input type="file" id="input-file">
</p>
<p>
<textarea id="content-target" style="width:440px;height:400px;"></textarea>
</p>
</body>
</html>
screenshot of text file uploader
You can add a button and call a function in your JavaScript. Something like
<button onclick="downloadText()">Download</button>
Being the function
function downloadText(){
var content = document.getElementById('content-target').value;
var dl = document.createElement('a');
dl.setAttribute('href', 'data:text/csv;charset=utf-8,' +
encodeURIComponent(content));
dl.setAttribute('download', 'text.txt');
dl.click();
}
Inside the function you should be able to do all the modifications you want. If you give more details, I can help you with the replace section of it, but it should be something like the following:
content.replace(regex, substitute);
More information here
Working CodePen

Categories

Resources