How do i take input from user and search api? - javascript

How can I take input (page number) from the user and then look for the corresponding text that has that page number and display it for the user using this API = https://api.alquran.cloud/v1/page/${number}/quran-uthmani

If I clearly understand you, then you need this:
async function getVersesforpage(number) { //to get verses for a certain pagetry
try {
const url = `https://api.alquran.cloud/v1/page/${number}/quran-uthmani`;
const response = await fetch(url);
const data = await response.json();
const ayahs = data.data.ayahs;
const verses = ayahs.map(ayah => ayah.text);
return verses;
} catch (e) {
console.log("Error:", e.message)
}
}
const form = document.getElementById("form");
form.addEventListener("submit", async(event) => {
event.preventDefault();
const {
number
} = event.target.elements;
const value = number.value;
const verses = await getVersesforpage(value);
console.log(verses);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>بصائر</title>
<link href="css/stylesheet1.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link href="css/img/logo1.png" rel="icon">
<script type="module"></script>
</head>
<body>
<header class="header">
<form id="form">
<label for="number">رقم الصفحة</label>
<input id="number" placeholder="Search.." type="number">
<button class="fa fa-search" type="submit"></button>
</form>
</header>
<!--<script src="https://unpkg.com/localbase/dist/localbase.dev.js"></script>-->
<script src="js/main.js"></script>
</body>
</html>

You can get the user value from any field by filed id using document.getElementById('idName').value.
I prefered to edit you code a bit now the below code returns the result from API.
async function getVersesforpage(pageNumber) {//to get verses for a certain pagetry
try {
const url = `https://api.alquran.cloud/v1/page/${pageNumber}/quran-uthmani`;
const response = await fetch(url);
const verses = await response.json();
return verses;
}
catch (e) {
console.log("Error:", e.message)
}
}
document.getElementById("form").addEventListener("submit", async (event) => {
event.preventDefault();
const pageNumber = document.getElementById('number').value;
const verses = await getVersesforpage(pageNumber);
console.log(verses.data);
});

Related

fetching data from json not showing on browser

this functionality is new to me, im building this with the help of a tutorial but since the tutorial fetched a different set of data i got lost.
const puppeteer = require('puppeteer');
const fs = require('fs');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://br.tradingview.com/symbols/TVC-DXY/',{
waitUntill: 'load',
timeout: 0
});
/*const element = await page.$(".tv-symbol-header__first-line");
const text = await page.evaluate(element => element.textContent, element);*/
const textNode = await page.evaluate(()=>{
const nodeText = document.querySelector(".tv-symbol-price-quote__change-value").innerText;
const text = [nodeText];
return text
});
fs.writeFile('arreglo.json', JSON.stringify(textNode), err =>{
if (err) throw new Error ('algo deu errado')
console.log('deu certo')
})
//await browser.close();
})();
<script>
(async() => {
const response = await fetch('./arreglo.json')
const data = await response.json();
document.querySelector(".container").innerHTML = data
})();
</script>
the first part is index.js
the second piece of code is in the html script.
the file arreglo.json is created and the result is like this:
["+0.887"]
i just want the 0.887, but i could format, not a problem, but i cant seem to get it on the html page.
It would be helpful to see the rest of your HTML code, or at least where you have placed the script tag as you have used a querySelector as part of the fetch request to render the data. Javascript code runs in order so if your script tag is before the ".container" element then your script will run before the ".container" element is available to render the data.
If you haven't already then I would place your script tags at the bottom of your HTML page so that all static content is rendered before any scripts start to amend it:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="container">
Content here...
</div>
<script>
(async() => {
const response = await fetch('./arreglo.json')
const data = await response.json();
document.querySelector(".container").innerHTML = data
})();
</script>
</body>
</html>

Javascript not working/loading properly after overlaying a new site over existing one

Basically I am trying to only give access to a certain page if a user has a certain item. After that is authenticated, the new page is only able to show basic HTML and CSS styling. The JavaScript does not seem to be loading at all... This is my index.html
const revealMsg = async () => {
var signature = await web3.eth.personal.sign("Message to sign", account)
console.log(signature)
var res = await fetch('/exclusive?signature=' + signature)
//console.log(res)
var body = await res.text()
//console.log(body);
if (body != 'FALSE') {
//console.log(body)
document.querySelector('html').innerHTML = body;
} else {
//alert you do not have item
alert("You do not have the item!");
}
}
This is my server.js
app.get('/exclusive', async (req, res) => {
isMember = false
var address = await web3.eth.accounts.recover("Message to sign", req.query.signature);
console.log(address)
var balanceOne = Number(await contractOne.methods.balanceOf(address).call())
var balanceTwo = Number(await contractTwo.methods.balanceOf(address).call())
console.log("Balance 1: ", balanceOne)
console.log("Balance 2: ", balanceTwo)
if(balanceOne > 0 || balanceTwo > 0){
isMember = true;
res.sendFile(path.join(__dirname, '/exclusive.html'))
}else{
res.send("FALSE")
}
})
And here is the exclusive page I am trying to test simple JS things
<!DOCTYPE html>
<html>
<head>
<title>Exclusive Page</title>
<script src="https://cdn.jsdelivr.net/npm/web3#latest/dist/web3.min.js"></script>
<style>
body {
background-color: red;
}
</style>
<h1>Hello World</h1>
<button onclick="clear()">Lost Tapes</button>
<button id="clear2">Clear2</button>
<script>
const clear = () => {
console.log('clear')
}
function clear2() {
console.log('clear2');
}
document.getElementById("clear2").onclick = clear2
</script>
</body>
</html>

Fetch API Not displaying Images properly - TV Show Website

I'm a beginner when it comes to coding and the biggest issue I have is to understand WHY something doesn't work (how to diagnose an error). I tried to combine what I learned from Colt Steele on Udemy with fetch API and so far, I've managed to make it work to list the NAMES of the movies when you search, but when I try to display the IMAGES, they seem to not work and it seems like it's trying to load them from my PC rather than from the TVMaze API. Here's my code:
function searchShow(query) {
const url = `https://api.tvmaze.com/search/shows?q=${query}`;
fetch(url)
.then(response => response.json())
.then((jsonData) => {
const resultsNames = jsonData.map(element => element.show.name);
const resultsImages = jsonData.map(e => e.show.image);
console.log(resultsNames);
renderResults(resultsNames);
console.log(resultsImages);
renderImages(resultsImages);
document.getElementById("errorMessage").innerHTML = "";
})
.catch((error) => {
document.getElementById("errorMessage").innerHTML = error;
})
}
function renderResults(resultsNames) {
const list = document.getElementById("resultsList");
list.innerHTML = "";
resultsNames.forEach(result => {
const element = document.createElement("li");
element.innerText = result;
list.appendChild(element);
});
}
function renderImages(resultsImages) {
const list2 = document.getElementById("imagesDisplay");
list2.innerHTML = "";
resultsImages.forEach(result => {
const imgShow = document.createElement("IMG");
imgShow.src = result;
list2.appendChild(imgShow);
})
}
let searchTimeoutToken = 0;
window.onload = () => {
const searchFieldElement = document.getElementById("searchField")
searchFieldElement.onkeyup = (event) => {
clearTimeout(searchTimeoutToken);
searchTimeoutToken = setTimeout(() => {
searchShow(searchFieldElement.value);
}, 250);
};
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TV Show</title>
</head>
<body>
<h1>TV Search</h1>
<input type="text" id="searchField" placeholder="Search a TV Show...">
<ul id="resultsList"></ul>
<ul id="imagesDisplay"></ul>
<div id=" errorMessage">
</div>
<script src="script.js"></script>
</body>
</html>
Can you please help me understand why is this not working and also, how can I make it display in a list like this:
-Name of the show
-Image of the show
-2nd name of the 2nd show
-2nd image of the 2nd show
etc.
Thank you in advance!
If you look at your images, you will see the src as [object Object] instead of the url to your image. You need to access the property of your object, in this case there's a few to choose from that represent different sized images.
I've modified your snippet to get what you want.
function searchShow(query) {
const url = `https://api.tvmaze.com/search/shows?q=${query}`;
fetch(url)
.then(response => response.json())
.then((jsonData) => {
let shows = jsonData.map(element => element.show);
renderShows(shows);
document.getElementById("errorMessage").innerHTML = "";
})
.catch((error) => {
document.getElementById("errorMessage").innerHTML = error;
})
}
function renderShows(shows) {
const list = document.getElementById("resultsList");
list.innerHTML = "";
shows.forEach(show => {
const element = document.createElement("li");
const img = document.createElement("img");
const text = document.createElement("span");
img.src = show.image.original;
text.innerText = show.name;
element.appendChild(text);
element.appendChild(img);
list.appendChild(element);
});
}
let searchTimeoutToken = 0;
window.onload = () => {
const searchFieldElement = document.getElementById("searchField")
searchFieldElement.onkeyup = (event) => {
clearTimeout(searchTimeoutToken);
searchTimeoutToken = setTimeout(() => {
searchShow(searchFieldElement.value);
}, 250);
};
}
img {
max-width: 100px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TV Show</title>
</head>
<body>
<h1>TV Search</h1>
<input type="text" id="searchField" placeholder="Search a TV Show...">
<ul id="resultsList"></ul>
<ul id="imagesDisplay"></ul>
<div id="errorMessage">
</div>
<script src="script.js"></script>
</body>
</html>

why is this not getting me the value of the input as the location?

I'm doing a weather app and I want that when the user inputs something, it should make the location change for the one that it was inputted. But when i try to work this code it doesn't work:
HTML:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<form id="form-input">
<input id="city-weather"/>
<button type="button" name="button">Search</button>
</form>
</body>
<script type="text/javascript" src="./script.js"></script>
</html>
Javascript:
function searchInput() {
var search = document.getElementById('form-input')
search.addEventListener("submit", (e) => {
e.preventDefault()
var id = document.getElementById("city-weather").value
})
}
async function getWeather() {
var location = searchInput()
try {
let response = await
fetch(`https://api.openweathermap.org/data/2.5/weather?q=${location}&appid=7d93c09c5bd7fccd41b0f335e310a15b`)
let user = await response.json()
console.log(user)
} catch(e) {
console.log(e)
}
}
This should work:
document.getElementById('form-input').addEventListener("submit", (e) => {
e.preventDefault();
var cityId = document.getElementById("city-weather").value;
getWeather(id);
})
}
async function getWeather(cityId) {
try {
let response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${cityId}&appid=7d93c09c5bd7fccd41b0f335e310a15b`)
let user = await response.json()
console.log(user)
} catch(e) {
console.log(e)
}
}
Explanation:
Your code had few mistakes:
No one was calling the function getWeather
You assumed searchInput would return a value while it would haven't
The attached code instead listens to the submission event on the global scope, and then calls the getWeather function giving it the cityId.

Searching for parks in one or more state

Im a new developer looking for help from someone with more experience. I'm trying to understand how to use a api/endpoint I created a key and now im trying to get my app to search for parks in one or more states and also display the full name, the description. Here's the api documentation. I hope I asked the question well enough I'm open to constructive criticism.
API (please copy and paste link in a new tab)
https://www.nps.gov/subjects/developer/api-documentation.htm#/parks/getPark
'use strict';
// put your own value below!
const apiKey = '';
const searchURL = 'https://developer.nps.gov/api/v1/parks?parkCode=acad&';
function formatQueryParams(params) {
const queryItems = Object.keys(params)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
return queryItems.join('&');
}
function displayResults(responseJson) {
// if there are previous results, remove them
console.log(responseJson);
$('#results-list').empty();
// iterate through the items array
for (let i = 0; i < responseJson.items.length; i++){
// for each video object in the items
//array, add a list item to the results
//list with the video title, description,
//and thumbnail
$('#results-list').append(
`<li><h3>${responseJson.items[i].snippet.title}</h3>
<p>${responseJson.items[i].snippet.description}</p>
<img src='${responseJson.items[i].snippet.thumbnails.default.url}'>
</li>`
)};
//display the results section
$('#results').removeClass('hidden');
};
function getYouTubeVideos(query, maxResults=10) {
const params = {
key: apiKey,
q: query,
part: 'snippet',
maxResults,
type: 'video'
};
const queryString = formatQueryParams(params)
const url = searchURL + '?' + queryString;
console.log(url);
fetch(url)
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error(response.statusText);
})
.then(responseJson => displayResults(responseJson))
.catch(err => {
$('#js-error-message').text(`Something went wrong: ${err.message}`);
});
}
function watchForm() {
$('form').submit(event => {
event.preventDefault();
const searchTerm = $('#js-search-term').val();
const maxResults = $('#js-max-results').val();
getYouTubeVideos(searchTerm, maxResults);
});
}
$(watchForm);
* {
box-sizing: border-box;
}
body {
font-family: 'Roboto', sans-serif;
}
button, input[type="text"] {
padding: 5px;
}
button:hover {
cursor: pointer;
}
.container {
max-width: 600px;
margin: 0 auto;
}
.error-message {
color: red;
}
.hidden {
display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>YouTube video finder</title>
<link rel="shortcut icon" href="#">
<link rel="stylesheet" href="index.css">
</head>
<body>
<div class="container">
<h1>Park finder</h1>
<form id="js-form">
<label for="search-term">Search term</label>
<input type="text" name="search-term" id="js-search-term" required>
<label for="max-results">Maximum results to return</label>
<input type="number" name="max-results" id="js-max-results" value="10">
<input type="submit" value="Go!">
</form>
<p id="js-error-message" class="error-message"></p>
<section id="results" class="hidden">
<h2>Search results</h2>
<ul id="results-list">
</ul>
</section>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<script src="index.js"></script>
</body>
</html>
'use strict';
// put your own value below!
const apiKey = 'XDkrghHigMG7xYtlfMloyKAoJ04H4te9h3UKWW3g';
const searchURL = 'https://developer.nps.gov/api/v1/parks?parkCode=acad&api_key=XDkrghHigMG7xYtlfMloyKAoJ04H4te9h3UKWW3g';
function formatQueryParams(params) {
const queryItems = Object.keys(params)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
return queryItems.join('&');
}
function displayResults(responseJson) {
// if there are previous results, remove them
console.log(responseJson);
$('#results-list').empty();
// iterate through the items array
for (let i = 0; i < responseJson.items.length; i++){
// for each video object in the items
//array, add a list item to the results
//list with the video title, description,
//and thumbnail
$('#results-list').append(
`<li><h3>${responseJson.items[i].snippet.title}</h3>
<p>${responseJson.items[i].snippet.description}</p>
<img src='${responseJson.items[i].snippet.thumbnails.default.url}'>
</li>`
)};
//display the results section
$('#results').removeClass('hidden');
};
function getYouTubeVideos(query, maxResults=10) {
const params = {
key: apiKey,
q: query,
part: 'snippet',
maxResults,
type: 'video'
};
const queryString = formatQueryParams(params)
const url = searchURL + '?' + queryString;
console.log(url);
fetch(url)
.then(response => {
(responseJson => displayResults(responseJson))
if (response.ok) {
return response.json();
console.log(response.json());
}
throw new Error(response.statusText);
})
.catch(err => {
$('#js-error-message').text(`Something went wrong: ${err.message}`);
});
}
function watchForm() {
$('form').submit(event => {
event.preventDefault();
const searchTerm = $('#js-search-term').val();
const maxResults = $('#js-max-results').val();
getYouTubeVideos(searchTerm, maxResults);
});
}
$(watchForm);
I can see a few things going on and I have some debug suggestions. Also, I would recommend cleaning up the Javascript so that it doesn't have a YouTube reference...
When you fetch(url) the first .then returns the json result but your call of the function doesn't do anything with the result. Presumably you would call displayResults, but you're not doing that (yet?). So at least console log response.json to see what's happening
You're use of two . then is incorrect. The first returns from the function so the second is never called. Get rid of the then and move the code into the first then
Debug suggestions - when you're stuck on something it's best to break it down into small steps and check the behavior from beginning to end
did you generate the right query url? You have console logged it which is good. Copy the url and paste into browser. Are you getting good json back? If not, go through the url building process step by step. Which reminds me, make sure you use your api key, it's set to "" in your code
check that your code is returning the same json as you got from the browser, if not, check whether anything is different between the browser call and the fetch
this should have got you past the point where you are stuck. Next step is to check the display function, and so on

Categories