User Input with API - javascript

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>

Related

Adding API output to HTML page

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.

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.

How to I call a function when form submit

Below is my part in my html page which is to get a threshold value and to call a function with the value
<form id="distance_input" onSubmit="return false;" >
<p>Enter a threshold</p>
<div class="col-md-8" style="display: inline-block; left:-30px">
<div class="col-md-4">
<div class="input-group">
<input type="text" class="form-control" id="usr" class="search" onkeydown="search(this)"> </input>
<span class="input-group-addon" style="width: 50px">km</span>
</div>
</div>
<div class="col-md-4" style="padding-left:0px; margin-left:-10px">
<input type="button" class="btn btn-success" value="Submit" id="myButton"> </input>
</div>
</div>
<p> </p>
</form>
<script type="text/javascript">
$('#myButton').click(function(){
var value = $("input[type=text]").val();
console.log(value+ " from the submit button");
set_to_threshold(value);
});
function search(ele) {
if(event.keyCode == 13) {
console.log(ele.value+" from enter button");
set_tothreshold(ele.value);
}
}
</script>
But when I do this I get the graphs do not get refreshed( set_tothreshold function gets new data for graph when the value is passes in the function) and shows that
Uncaught ReferenceError: search is not defined
at HTMLInputElement.onkeydown
when I tried with
<script type="text/javascript">
$('#myButton').click(function(){
var value = $("input[type=text]").val();
console.log(value+ " from the submit button");
set_to_threshold(value);
});
</script>
also when I press submit button no changes happened(even does not prints value in console).But why does the value does not get printed.Any help is appreciated.
$('#myButton').click(function(){
var value = $("input[type=text]").val();
console.log(value);
set_to_threshold(value);
});
function set_to_threshold(val){
console.log('do something here with val ', val);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<input type="text" value="input something"/>
<button id="myButton">click</button>
</body>
</html>
this is what you want . yourfunction call when form submit
<form id="distance_input" onSubmit="yourFunction(); return false;" >
Kindly include jquery in your file. It works fine.
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
Include this at the head section of the html page. And also there u referred function set_to_threshold() which is undefined. So only you are getting the error. Kindly write a function for it. it'll work!

Display form data from angular on a server using $http

I am using a form in html, using angular, and binding the username and email id of the user.
I wish to display the details of the particular user onto a server page, where in when a user clicks on Submit details on the front end, the data is "binded" and the information is simultaneously shown on the server page.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<link href='https://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<title>Random title here</title>
<body ng-app="test" ng-controller="mainctrl as ctrl">
<div class="container">
<div class="col-sm-8 col-sm-offset-2">
<form name="userform" ng-submit="ctrl.submit()">
<div class="form-group">
<label> Name</label>
<input type="text" name="name" class="form-ctrl" ng-model="ctrl.user.name">
</div>
<div class="form-group">
<label> Email id</label>
<input type="email" name="email" class="form-ctrl" ng-model="user.email">
</div>
<button type="submit" class="btn btn-primary"> Submit </button>
</form>
</div>
</div>
<script>
var test=angular.module('test',[]);
test.controller('mainctrl',[function($scope,$html){
$scope.user={};
$scope.submit= function () {
$http({
method : 'POST',
url : 'test1.java', //No idea what to put here. Help pls.
data : $scope.user;
headers : {'Content-Type':'application/x-www-form-urlencoded'}
}).success(function(data)
{
console.log("Success");
});
}
}]);
</script>
</body>
</html>
This is just a sample of code I typed. As a beginner, any help would be appreciated. Thanks.
If you are using controller as syntax than you should write your function with reference this. Your controller snippet would be like
angular.module('test',[])
.controller('mainctrl',[function($scope, $http){
var cm = this;
cm.user={};
cm.submit= function () {
$http({
method : 'POST',
url : form.attributes['target'],
data : cm.user;
}).success(function(data)
{
console.log("Success");
});
}
}]);
and pass the form element in your ng-submit directive. Like
<form name="userform" ng-submit="ctrl.submit($element.action)">
I hope my code will be usefull for you!
View:
<body ng-controller="UserDataController">
<form ng-submit="sendData(user)">
<input type="text" placeholder="name" ng-model="user.name" />
<input type="text" placeholder="second name" ng-model="user.second_name" />
<button type="submit" class="btn btn-sm btn-primary">
Save
</button>
</form >
Cotroller:
angular.module('httpExample', [])
.controller('UserDataController', ['$scope', '$http', function($scope, $http) {
$scope.user = {};
$scope.sendData= function(user) {
$http.post("/SomeUrl", user).success(function(data, status) {
console.log(data);
console.log(status);
$scope.data = data;
// now you can write {{data}} at your veiw
// example {{data.id}}
});
}]);
Example: get request

Submit button not working on login form, using PHP and JavaScript

I am trying to code a simple login page using JavaScript and PHP to help validate the user input values with the values in a database.
However, my submit button doesn't seem to do anything... it just clears the fields.
Here is my code. There are probably MANY errors in it and I apologize for that... the PHP code I wrote is from a collection of other login pages I found on the web and I only started learning JavaScript a couple days ago...
EDIT: I have updated the code based on the mistakes that you guys pointed out. The log in button now no longer refreshes but instead doesn't do anything. I will try to figure it out or start from scratch since there is so much code that I don't understand, haha.
login.html:
`<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="bootstrap.min.css">
<link type="text/css" rel="stylesheet" href="stylesheet.css" />
<title>Login</title>
</head>
<body>
<div class="header">
<div class="container">
<h1>Login</h1>
</div>
</div>
<div class="form">
<form class="form-horizontal">
<div class="form-group">
<div class="col-sm-10">
<input type="text" class="form-control" id="inputUsername3" name="username" placeholder="Username">
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<input type="password" class="form-control" id="inputPassword3" name="password" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class=" col-sm-10">
<div class="checkbox">
<label>
<input type="checkbox">Remember me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<input id="submit" type="submit" class="btn btn-default" value="Log in">
</div>
</div>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="js/vendor/jQuery.md5.js"></script>
<script src="login.js"></script>
</div>
</body>
</html>'
login.js
$(document).ready(function(){
$("form").on("submit", function(e){
e.preventDefault();{
var username = $('#inputUsername3').val();
var password = $('#inputPassword3').val();
var newPw = $.md5(password);
if (username != "" && password !="") {
$.ajax ({
url: "doLogin.php",
type: "POST",
async: false,
data: "$username="+username+"&password="+newPw,
success: function(result) {
window.open(success.html);
}
});
} else {
alert("Please enter a username and password.");
}
return false;
});
});
doLogin.php:
<?php
$host="localhost";
&username="";
$password="";
$db_name="atasgtsar";
$tbl_name="members";
$connection =
mysqli_connect("$host", "$username", "$password")or die("Unable to connect.");
mysqli_select_db("$db_name");
$myUsername=$_POST['username'];
$myPassword=$_POST['password'];
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysqli_real_escape_string($myusername);
$mypassword = mysqli_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysqli_query($sql);
$count=mysqli_num_rows($result);
if ($count == 1) {
session_register("myusername");
session_register("mypassword");
}
else {
echo "Wrong username or password.";
}
mysqli_close($connection);
?>
Your fields are cleared as the submit button reloads the page.
Use preventDefault(); to stop the submit from happening as you want to submit the data yourself using ajax.
$("form").on("submit", function(e){
e.preventDefault();
//...
Please do not store passwords as plain text in databases, use password_hash() and password_verify().
The MySQL Version you use is deprecated, please use MySQLi or PDO.
There is no type='username', use 'text'.
You call "check(this.form)" from the submit button, but you already bind the jQuery handler to the submit event using js.
If you want to select elements by there ID in jQuery, instead of input[id=username], use #username
Also, there sure are more mistakes in these codes.
I would always recommend to start with an extremely basic layout, print out all information (in js using console.log or alert and in php using echo) and then go n small steps, until you got your working code.
You read out the wrong input fields in your JS and remove the $ in your data string which will send via post.
Here is the correct version.
$(document).ready(function(){
$("#submit").click(function(){
var username = $('input[id=inputUsername3]').val();
var password = $('input[id=inputPassword3]').val();
var newPw = $.md5(password);
if (username != "" && password !="") {
$.ajax ({
url: "doLogin.php",
type: "POST",
async: false,
data: "username="+username+"&password="+newPw,
success: function(result) {
alert(result)
}
});
}
else {
alert("Please enter a username and password.");
}
return false;
});
});
You have also forget the " on the end of the ID.
<div class="col-sm-10">
<input type="username" class="form-control" id="inputUsername3" name="username" placeholder="Username">
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<input type="password" class="form-control" id="inputPassword3" name="password" placeholder="Password">
</div>
</div>
You have done too many mistakes in HTML and Javascript coding:
<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="bootstrap.min.css">
<link type="text/css" rel="stylesheet" href="stylesheet.css" />
<title>Login</title>
</head>
<body>
<div class="header">
<div class="container">
<h1>Login</h1>
</div>
</div>
<div class="form">
<form class="form-horizontal">
<div class="form-group">
<div class="col-sm-10">
<input type="text" class="form-control" id="inputUsername3" name="username" placeholder="Username">
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<input type="password" class="form-control" id="inputPassword3" name="password" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class=" col-sm-10">
<div class="checkbox">
<label>
<input type="checkbox">Remember me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<input id="submit" type="submit" class="btn btn-default" value="Log in">
</div>
</div>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="js/vendor/jQuery.md5.js"></script>
<script src="login.js"></script>
</div>
</body>
</html>
Than in your javascript code:
$(document).ready(function(){
$("#submit").click(function(){
var username = $('#inputUsername3').val();
var password = $('#inputUsername3').val();
var newPw = $.md5(password);
if (username != "" && password !="") {
$.ajax ({
url: "doLogin.php",
type: "POST",
async: false,
data: "$username="+username+"&password="+newPw,
success: function(result) {
alert(result)
}
});
}
else {
alert("Please enter a username and password.");
}
return false;
});
});
In the HTML the "tpye" attribute of the input with name "username" should be "text" and you've forgot to close the quotes after the "id" attribute:
<input type="text" class="form-control" id="inputUsername3" name="username" placeholder="Username">
In your Javascript it seems like you use jQuery but I dont see where you include the library.
The javascript selectors for IDs should be defined like this:
var username = $('#inputUsername3').val();
var password = $('#inputPassword3').val();
Keep in mind that there could be more things that I haven't notice.
The browser automatically posts your data when you click in an submit button that is inside your form, what you have to do is to prevent this default behaviour so that it actually uses your JS code.
change
$("#submit").click(function(){
for
$("form").on("submit", function(e){
e.preventDefault();
Your fields are beeing cleared because your button is a submit button and because you are not redirecting the client to any other page, it refreshes it. From what I see you want to use AJAX, try to use just a simple button with a onclick event (type="button").

Categories