Adding API output to HTML page - javascript

I'm trying to make a food bank finder for food banks in California. The API data can be found here. So far, the data opens up on a separate tab (due to the target being "_blank") But I would want the data to output on the screen once the user presses the button, and only specific parts of the data (the name and address of the food bank). How would I show the output on the website and only specific parts of the data? Thank you for your time
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://controllerdata.lacity.org/resource/v2mg-qsxf.json"></script>
<title>Sample Page</title>
<div class="w3-row w3-padding-64 spacing" id="location">
<div class="w3-col l6 w3-padding-large, spacing">
<h1 class="w3-center">Find a location</h1><br>
<h5>Enter you zip code below</h5>
</div >
<div class = "relative">
<form action="https://controllerdata.lacity.org/resource/v2mg-qsxf.json" target="_blank" method="get" >
<label for="zip_code">Zip Code:</label>
<input type="number" id="zip_code" name="zip_code"><br><br>
<input type="submit" value="Submit">
</form>
</div>
</html>

This is my suggestion:
var form = document.getElementById('form');
var output = document.getElementById('output');
form.onsubmit = () => {
var zip_code = document.getElementById('zip_code').value;
fetch('https://controllerdata.lacity.org/resource/v2mg-qsxf.json?zip_code=' + zip_code)
.then(res => res.json())
.then(res => {
output.innerHTML = res[0].name + ' - ' + res[0].street_address;
});
return false;
};
<form id="form">
<label for="zip_code">Zip Code:</label>
<input type="number" id="zip_code" name="zip_code"><br><br>
<input type="submit" value="Submit">
</form>
<br>
<div id="output"></div>
It shows desired results (name and address) on the same page (try, for example, zip code 94501).

Your current solution seems fully HTML based. I think that you can best do this in JavaScript however, doing an asynchronous request for the data using the API like this:
fetch('https://controllerdata.lacity.org/resource/v2mg-qsxf.json')
.then((res) => res.json())
.then((data) => {
// do something with data here
console.log(data)
});
You can add a button that triggers a JS function to search in the retrieved data.

Related

How to get html form values and pass it into js function parameters which will execute a js function that will perform calculations with those values

I am new to coding as whole and I am just trying to do some exercises devised by myself to get familiar with stuff. Currently I have written a JS function that takes input and calculates monthly expenses, I've also written a simple html markup for a form that will get those values. Essentially I want to combine those two things together and print out the result in the same html doc.
The JS function:
function testing(input){
let income = Number(input[0]);
let savings = Number(input[1]);
let rent = Number(input[2]);
let credit = Number(input[3]);
let subs = Number(input[4]);
let food = Number(input[5]);
let car = Number(input[6]);
let others = Number(input[7]);
let sum = income - (rent + credit + subs + food + car + others);
let sum1 = sum - savings;
console.log(`\nExpenses this month: ${sum.toFixed(2)}\nSavings this month: ${savings.toFixed(2)}\nMoney left: ${sum1.toFixed(2)}`);
}
The form markup:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>
Calculator for monthly salary and expenses
</title>
</head>
<body style="text-align: center;">
<h1 style="color: rgb(0, 19, 128);">
Calculator
</h1>
<h3>Input the data in the corresponding fields</h3>
<form>
<label for="salary">Salary:</label><br>
<input type="text" id="salary" name="salary"><br><br>
<label for="savings">Savings:</label><br>
<input type="text" id="savings" name="savings"><br><br>
<label for ="rent">Rent:</label><br>
<input type="text" id="rent" name="rent"><br><br>
<label for ="debt">Debt:</label><br>
<input type="text" id="debt" name="debt"><br><br>
<label for ="subs">Subscriptions:</label><br>
<input type="text" id="subs" name="subs"><br><br>
<label for ="food">Food:</label><br>
<input type="text" id="food" name="food"><br><br>
<label for ="car">Car expenses:</label><br>
<input type="text" id="car" name="car"><br><br>
<label for ="others">Others:</label><br>
<input type="text" id="others" name="others"><br><br><br>
<input type="submit" id="submit" name="submit"><br>
</form>
I did find something (but I don't understand it fully) that converts the form inputs to an object but then they are stored as an object with key - value and I am not sure how translate that into function parameters that will call the function and perform the calculations.
<script>
const form = document.querySelector('form');
form.addEventListener('submit', (e) => {
e.preventDefault();
const fd = new FormData(form);
const obj = Object.fromEntries(fd);
console.log(obj)
});
</script>
Any input or guidelines are much appreciated. Thank you!!!
I've tried getting user input from html form and converting it into js function parameters to call a function that will perform calculations with that data. Not sure how to achieve this.

JavaScript - URL parameters not populating on next page

I have a radio button with specific values that I want to include in my URL parameters for the following pages (more than one). I have the parameters set up in the JS as var params.
in my, if-statement I have a console.log and location.href set to the next page desired based on the result.
my issue is when I press the button it takes me to the page but not with the desired parameters.
I also have 5 pages for each result following this page. how can I append the parameters to the following pages?
EPP1.HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Create Custom Evaluation Portal</title>
</head>
<body>
<div id="bodyText"></div>
<form id="myForm" action="EPV3.html" method="get">
<div id="pBFContainer">
<div id="bodyFOption1">
<label for="email">Enter email address:<p></label>
<input type='text' id='inputEmail' name='email' size="70"></input></div>
<div id="bodyFTitle2"></div>
<div id="bodyFOption2">
<label for="testType">Choose the test theme for your evaluation:<p></label>
<input id='rb1' class="optionT" type='radio' name='testType' value='voip' checked>VoIP<p>
<input id='rb2' class="optionT" type='radio' name='testType' value='bandwidth'>Bandwidth<br><br>
</div>
<div id="bodyFTitle3"></div>
<div id="bodyFOption3"></div>
</div>
<input type="submit" id="subButton" value="Next..." />
</form>
</body>
<script type="text/javascript" src="EPP1.js"></script>
</html>
EPP1.js:
window.addEventListener("load", () => {
let qs = decodeURIComponent(location.search.substring(1));
let params = new Map();
let parts = qs.split("&");
parts.forEach((part) => {// i got this from a tutorial and liked it
let key = part.split("=")[0];
let val = part.split("=")[1];
params.set(key, val);
});
if (params.get("testType") == "voip") {
console.log("testtype is voip");
window.location.href = "EvalPortalV3.html";
} else if (params.get("testType") == "bandwidth") {
console.log("testtype is bandwidth");
window.location.href = "EvalPortalB3.html";
}
});

How to run a function in input tags value attribute

I have an html page that i send to a client as response when he wants to transfer money
response.end(
`
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>The Good Server</title>
</head>
<body>
<p>Transfer money to other users with the super safe form which uses the latest HTTP GET method!</p>
<form action="/money_transfer" method="get">
<div class="container">
<label for="from"><b>Tranfer from</b></label>
<input type="text" value="good_user" name="from" required readonly>
<label for="to"><b>Transfer to</b></label>
<input type="text" placeholder="User you want to send money to" name="to" required>
<label for="sum"><b>Sum to transfer (in full Euros)</b></label>
<input type="number" placeholder="Enter a sum" name="sum" required>
<input name="csrf_token" type="hidden" value="setCSRFtoken()">
<button type="submit">Transfer money</button>
</div>
</form>
</body>
</html>
`
);
I try to get the an randomly generated token and set it as a value for the input tag as is shown before the button: Transfer money. My setCSRFtoken function also stores the token into an array.
const setCSRFtoken = () => {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < 10; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
console.log(result)
csrfTokens.push(result);
return result;
The value that returns from the setCSRFtoken function must be placed in to the input's(name=crsf_token) value.
The problem is that at the moment i cant get the function to run in the page and return the randomly generated value. i also thought about adding the value as parameter to the page but dont know how add it to the response.
<input name="csrf_token" type="hidden" onload="this.value=setCSRF()">
Saw the code above as an fix but it didn't work for me

How do I send my form information, on submit, to my email with emailjs?

I'm working on my project and I have a form that you fill out your name and email and then press submit. So far so good. The problem is that I'm trying to when the user presses "submit" the information that was filled in the form (name and email) go to my personal email. I'm currently using Emailjs because it was recomended by my school, but it's not working and I don't understand what I'm doing wrong. Here's what I've done so far:
//I put this is the end of the <head> section
<script type="text/javascript" src="https://cdn.emailjs.com/sdk/2.2.4/email.min.js"></script>
<script type="text/javascript">
(function() {
emailjs.init("user_"); //it has my user ID, just didn't want to share
})();
</script>
//this is the form
<form id="testform" onsubmit="return sendMail(this);">
<div class="box">
<label for="fullname" class="form-tag">Name</label>
<input type="text" name="name" id="fullname" class="form-control" required/>
<label for="emailaddress" class="form-tag">Email</label>
<input type="email" name="email" id="emailaddress" class="form-control" required/>
<div class="button">
<button id="submit" type="button" class="btn btn-light btn-lg">Submit</button>
</div>
</div>
</form>
//and this is right before the end of the
<script src="assets/js/sendEmail.js"></script>
//the sendEmail.js
function sendMail(contactForm) {
emailjs.send("gmail", "yourjourney", {
"from_name": contactForm.name.value,
"from_email": contactForm.emailaddress.value,
})
.then(
function(response) {
console.log("SUCCESS", response);
},
function(error) {
console.log("FAILED", error);
}
);
return false; // To block from loading a new page
}
so you have two issues in your code.
First your button is type button beside type submit.
Second you are using return false which means you stop the submitting proccess.
for you to be able to make it work without the page reloading you don't have to create a form.
It will be a bit different than what the school teaches you, but i hope it will help.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type='text/javascript' src='https://cdn.jsdelivr.net/npm/emailjs-com#2/dist/email.min.js'></script>
<script type='text/javascript'>
(function () {
emailjs.init('user_ID');
})();
</script>
<title>Document</title>
</head>
<body>
<div class="box">
<label for="fullname" class="form-tag">Name</label>
<input type="text" name="name" id="fullname" class="form-control" required />
<label for="emailaddress" class="form-tag">Email</label>
<input type="email" name="email" id="emailaddress" class="form-control" required />
<div class="button">
<button id="button" type="button" class="btn btn-light btn-lg">Submit</button>
</div>
</div>
<script src="assets/js/sendEmail.js"></script>
</body>
</html>
JS (sendEmail.js file):
//Getting the name and email from the DOM
let fullName = document.getElementById('fullname').value
let email = document.getElementById('emailaddress').value
//Getting the button from the DOM
let submitButton = document.getElementById('button')
//Add event listener on click to the button - notice i added the event as argument to the function
submitButton.addEventListener('click', function(event){
//prevent the reload of the page. here i prevent the event.
event.preventDefault()
//Sending the email with the name and email
emailjs.send("gmail", "yourjourney", {
"from_name": fullName,
"from_email": email,
})
.then(
function (response) {
console.log("SUCCESS", response);
},
function (error) {
console.log("FAILED", error);
}
);
})
If you must have the form and its part of homework or something let me know so i can change the code according to what you are learning.
//Getting the button from the DOM
let submitButton = document.getElementById('button')
//Add event listener on click to the button - notice i added the event as argument to the function
submit.addEventListener('click', function(event){
//prevent the reload of the page. here i prevent the event.
event.preventDefault()
//Getting the name and email from the DOM
let fullName = document.getElementById('fullname').value
let email = document.getElementById('emailaddress').value
//Sending the email with the name and email
emailjs.send("gmail", "yourjourney", {
"from_name": fullName,
"from_email": email,
})
.then(
function (response) {
console.log("SUCCESS", response);
},
function (error) {
console.log("FAILED", error);
}
);
})
Thank you #elnatan vazana for helping me!
My user ID was incorrect, so I changed it and now it workd fine. I'm able to receive the information that is submitted to the form.

User Input with API

I have a form where a user can input the latitude and longitude (coordinate).
What i want to do is to display the information based on the below REST API:
https://rest.soilgrids.org/query.html
So here is what i created.
<p>
Latitude : <input id='lat'/> <br/>
Longitude: <input id='lon'/> <br/>
<button id='submit'>Submit<button/>
<p/>
So how do i extract the input and and made it display the information that are available based on the API. I am beginner in this so would need help in JS
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<style>
</style>
<title>Untitled Document</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm-6">
<label>Latitute</label>
<input type="number" class="form-control" id="lat">
</div>
<div class="col-sm-6">
<label>longitute</label>
<input type="number" class="form-control" id="long">
</div>
<div class="col-sm-3">
<input type="button" class="btn btn-primary" id="search" value="get Info">
</div>
</div>
</div>
<script>
$(document).ready(function(){
$("#search").click(function(){
let lat = $("#lat").val();
let long = $("#long").val();
if(lat == "" || long==""){
alert("please enter lat and long to get info");
return;
}
else{
$.ajax({
type:"GET",
url:`https://rest.soilgrids.org/query?lon=${long}&lat=${lat}`,
dataType: "json",
success:function(response){
console.log(response);
},
error:function(jqXHR, exception){
console.log("error");
}
})
}
})
})
</script>
</body>
</html>
Try it
You will need to perform an Ajax call to get data from an API.
Assuming that you have jQuery in your script, an example will be:
// The code will only run on form submit
$("#form").on("submit", (evt) => {
evt.preventDefault();
// Abbreviate on how you get the longitude / latitude
const longitude = ...
const latitude = ...
const url = "https://rest.soilgrids.org/query?lon=" + logitude + "&lat=" + latitude
$.ajax(url, {
method: "GET" // You need to read the documentation of the API provider to see if it is a POST or GET call
// There are more option that you can set. Read the documentation of jquery,
success: (data) => {
// This is where you perform effect after you get the data from API
}
})
})
See https://api.jquery.com/jquery.ajax/ for more detail
Edit
Just saw your code. Some minor change should be made to make this better:
// Warp it into a <form> block so that it will response to "Enter" Key
<form id="form">
Latitude : <input id='lat'/> <br/>
Longitude: <input id='lon'/> <br/>
// Good habit to state the type of a button
<button type="submit" id='submit'>Submit<button/>
</form>

Categories