I am new to node.js and I'm trying to create an easy way for a user to input data into an html form, then on the click of submit the data is passed to a node.js script. The node.js script is a post script that takes the user's inputed data and then makes a post to a API and takes a return in JSON from the API. I am trying to get the returned JSON to be printed back onto the html page. How do you do this in a clean and easy manner?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Commute | Ad-hoc</title>
<link rel="stylesheet" href="css/style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div class="container cf">
<div class="container cf">
<div>
<h1>Manual Query</h1>
<label>Mode</label>
<select id="modes">
<option value="driving">Driving</option>
<option value="walking">Walking</option>
<option value="cycling">Cycling</option>
</select>
<label>Latitude Origin</label>
<input type="text" name="latitude_origin" id="latitude_origin" value="37.791871">
<label>Longitude Origin</label>
<input type="text" name="longitude_origin" id="longitude_origin" value = "-122.396742">
<label>Latitude Destination</label>
<input type="text" name="latitude_dest" id="latitude_dest" value = "37.782461">
<label>Longitude Destination</label>
<input type="text" name="longitude_dest" id="longitude_dest" value = "-122.454807">
<button id="singleQuery" class="singleQuery" input type="default small">Run</button>
</div>
<div>
<h1>Multi-Query (.tsv)</h1>
<label>Upload</label>
<input type="file" name="pic" id="laserPrinters">
<button id="testLaser" class="default small" input type="default small">Run</button>
</div>
<div>
<h1>Result</h1>
<textarea rows="4" cols="50"> </textarea>
</body>
</html>
<script type="text/javascript">
var mode = $("#modes").val();
var latitude_origin = $("#latitude_origin").val();
var longitude_origin = $("#longitude_origin").val();
var latitude_dest = $("#latitude_dest").val();
var longitude_dest = $("#longitude_dest").val();
</script>
My Node.JS post script:
var request = require("request");
var options = { method: 'POST',
url: 'http://blah:8000/blah/blah/blah/blah/[latitude_origin]/[longitude_origin]/',
headers:
{ 'postman-token': 'blah',
'cache-control': 'no-cache' },
body: '{"query1":[latitude_dest,longitude_dest]}' };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
First, you have to setup a server to listen to the requests that you will send to your node.js web api.
I really like recommend you use express.js. It is a very powerful web server.
Read more in:
https://expressjs.com/
I am writing some example for you soon.
Hope it help you.
UPDATE 1
Take a look at MEAN Stack
https://github.com/meanjs/mean
UPDATE 2
Here are some examples:
https://scotch.io/tutorials/setting-up-a-mean-stack-single-page-application
https://developers.openshift.com/languages/nodejs/example-meanstack.html
Related
I have created a small website using HTML service of Google apps script.
Here is GAS Code
function doGet() {
var t = HtmlService.createTemplateFromFile('form');
t.email=Session.getActiveUser().getEmail();
return t.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
and this is HTML Code
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<base target="_top">
</head>
<body onLoad="addEventListeners()">
<div class="container-fluid">
<form id="form1">
<label for="comp_indiv_name" id="company_individual_name" style="display: block" >2. COMPANY NAME</label>
<input type="text" class="form-control" name="cName" required>
<br>
<input type="submit" class="btn btn-primary" value="Create Contract Now">
</form>
</div>
<script>
function addEventListeners() {
var condition=true;
document.getElementById('form1').addEventListener('submit', function(e){
e.preventDefault();
if(condition==true){condition=false;google.script.run.addData(this);}});
}
</script>
</body>
</html>
HTML page has one form with just one question, and when that form is submitted, the value get written in spreadsheet. Code for that is
function addData(form)
{
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sheet=ss.getSheetByName('test');
sheet.getRange(5,5).setValue(form.cName)
htmlPage();
}
All i want is once the value gets written on the sheet, this HTML page gets refreshed automatically. Right now it just stays as it is. Link to the HTML page is https://script.google.com/macros/s/AKfycbzavm6TPFOkIXj_V0uD8XIqMN-9w6jAgp_QgRkJXawFJF59rPU/exec
If you truly want to refresh the page, and not just clear the input field, then I would add a hidden link that has your web app URL, and then programatically "click" it when the server code has completed.
HTML
</form>
<a id="linkToThisWebApp" href="https://script.google.com/macros/s/webAppID/exec" style="display:none">Hidden</a>
<!-- <button onclick="reloadPg()">Test</button> -->
</div>
Script tag - Code with success handler
<script>
function addEventListeners() {
var condition=true;
document.getElementById('form1')
.addEventListener('submit',
function(e){
e.preventDefault();
if(condition==true){
condition=false;
google.script.run
.withSuccessHander(reloadPg)
.addData(this);
}
});
}
window.reloadPg = function() {//Runs when server code has completed
console.log('reloadPg ran');
document.getElementById('linkToThisWebApp').click();//Click the link
}
</script>
I am having trouble actually returning any kind of object using this AJAX call. I know I am doing something wrong, but I have no idea where. I hope someone can help me I am looking to return an element in the object "zip". I would like to have any response really, but I can not get anything back.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function() {
var result = $('#resultDiv')
$.ajax({
url: 'https://us-street.api.smartystreets.com/street-address',
method: 'get',
data: {
auth-id='your-auth-id',
auth-token='your-auth-token',
street=$('#street'),
city=$('#city'),
state=$('#state')
},
dataType: 'json',
success: function(data) {
if (data = null)
{
result.html('You failed');
}
else {
result.html('Match:' + data.components[0].zipcode)
}
}
});
});
});
</script>
<title>SSTest</title>
</head>
<body>
<div class="container">
<h1 style="text-align:center"> Welcome to Address Check </h1>
<form action="#" method="post">
<div class="form-group">
<label for="street">Street</label>
<input type="text" id="street" class="form-control" name="street">
</div>
<div class="form-group">
<label for="city">City</label>
<input type="text" id="city" class="form-control" name="city">
</div>
<div class="form-group">
<label for="state">State</label>
<input type="text" id="state" class="form-control" name="state">
</div>
<button type="submit" id="submit" class="btn btn-default">Submit</button>
<br/>
<br/>
<div id="resultDiv"></div>
</body>
</html>
As you are using a GET call, you can test this in the browser first AND make sure you are getting a response before you start wrapping it in a JQuery call.
https://us-street.api.smartystreets.com/street-address?auth-id=[your-auth-id]&auth-token=[your-auth-token]&street=SOMETHING&state=SOMETHING&city=SOMETHING
If you get a non-result, then consult the API to see if you are passing the correct parameters.
Using the DOCS, this call returns data for your API Keys -
https://us-street.api.smartystreets.com/street-address?auth-id=[your-auth-id]&auth-token=[your-auth-token]&street=1600+amphitheatre+pkwy&city=mountain+view&state=CA&candidates=10
This JQuery Get HTML example gets a response -
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.get("https://us-street.api.smartystreets.com/street-address?auth-id=[your-auth-id]&auth-token=[your-auth-token]&street=1600+amphitheatre+pkwy&city=mountain+view&state=CA&candidates=10", function(data, status){
alert("zipcode: " + JSON.stringify(data));
});
});
});
</script>
</head>
<body>
<button>Send an HTTP GET request to a page and get the result back</button>
</body>
</html>
You should be able to build from that as you refine your JQuery understanding to get exactly what you need.
I was able to find a handful of errors with your code and fixed them here in this JSFiddle. Here are the list of errors you had.
Don't include your auth-id, auth-token in public code. You're giving away your address lookups by doing this. You should go remove these from your account and generate new ones.
In your original success function you didn't do a compare. You should use == here. Actually, the API will never send back null for data on success so you don't even need this here anymore. Use the error function instead.
The data object passed in the ajax call is done incorrectly. You should not be using =, instead use :.
In the data object you should call .val() after the jQuery selectors to get the values entered into those fields.
data.components[0].zipcode should be data[0].components.zipcode. The api will return back a data array of objects. components is not an array.
The auth-id and token should only be used when used from server side.
It is clearly mentioned not to expose the auth-id and auth-token in the documentation.
I used the FETCH API from Javascript and the code looks like this:
var key = '' //your embedded key here
var street = encodeURIComponent('1600 amphitheatre pkwy');
var city = encodeURIComponent('mountain view');
var state = 'CA';
var url = 'https://us-street.api.smartystreets.com/street-address?street=' + street + '&city=' + city + '&state=' + state + '&key=' + key;
const response = await fetch(url)
const responseData = await response.json()
I am working through learning feathers and I am trying to send some data to a service I created. It works fine when I use it without any authorization. When I add authorization I can send the JWT token manually with postman. However when I send a post I am not sure how to send the token in the header or the best way to handle this. The example I have found uses socket.io. Is there a way to do this with a simple post?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=0">
<title>Feathers Chat</title>
<link rel="shortcut icon" href="favicon.ico">
<link rel="stylesheet" href="//cdn.rawgit.com/feathersjs/feathers-chat/v0.1.0/public/base.css">
<link rel="stylesheet" href="//cdn.rawgit.com/feathersjs/feathers-chat/v0.1.0/public/chat.css">
</head>
<body>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript" src="//unpkg.com/feathers-client#^1.0.0/dist/feathers.js"></script>
<script type="text/javascript">
var host = 'http://localhost:3030';
// Set up Feathers client side
var app = feathers()
.configure(feathers.rest(host).jquery(jQuery))
.configure(feathers.hooks())
.configure(feathers.authentication({ storage: window.localStorage }));
// authenticate using your JWT that was passed in the short lived cookie
app.authenticate().then(function(result){
console.log('Authenticated!', result);
alert('Your JWT is: ' + app.get('token'));
}).catch(function(error){
console.error('Error authenticating!', error);
});
</script>
<main class="login container">
<div class="row">
<div class="col-12 col-6-tablet push-3-tablet text-center">
<h1 class="font-100">Post</h1>
</div>
</div>
<div class="row">
<div class="col-12 col-6-tablet push-3-tablet col-4-desktop push-4-desktop text-center">
<form class="form" method="post" action="/posts">
<fieldset>
<input class="block" type="text" name="title" placeholder="title">
</fieldset>
<fieldset>
<input class="block" type="text" name="description" placeholder="description">
</fieldset>
<button type="submit" class="button button-primary block login">
Post
</button>
</form>
</div>
</div>
</main>
</body>
</html>
Thanks for any help! I really like feathers so far.
Ok so this is what I did and seems to work fine. I wasn't sure if feathers was somehow automagically handling the auth token after it was created. Once I setup the post to send via jquery and setup the authorization header it worked fine. Thanks for all the help. I do like feathers a lot so far!
$(document).ready(function() {
$( ".test-form" ).submit(function( event ) {
var token = app.get('token');
event.preventDefault();
$.ajax({
url: 'http://localhost:3030/posts/',
type: 'post',
data: {
title: $("#title").val(),
description: $("#description").val()
},
headers: {
Authorization: token
},
dataType: 'json',
success: function (data) {
console.info(data);
}
});
});});
Use the Feathers client. The same app you're using to do authentication.
// Get the Posts service to work with
var postsService = app.service('posts');
// Create a post
postsService.create({
title: $('#title').val(),
description: $('#description').val()
});
// Do something when a Post is created
postsService.on('created', function (post) {
// `post` is the newly created post
// this callback will run whenever a post is created
console.log(post);
});
You could even use the postsService.create method in an event handler, something likeā¦
$('form').on('submit', function () {
postsService.create({
title: $('#title').val(),
description: $('#description').val()
});
});
Read this section: http://docs.feathersjs.com/authentication/client.html
You can get token with app.get('token').
when you post the data, set the header field in Authorization -> token which you get when you login.
Im in the process of adding the reCaptcha from google to my form. The problem is that even though I have followed the instructions from google. I can still press the Submit button without doing the recaptcha. Any Ideas please heres the relevant code snippets.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>webpage title</title>
<link rel="stylesheet" type="text/css" href="view.css" media="all">
<script type="text/javascript" src="view.js"></script>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
And the this snippet in the form part of the webpage
<div class="g-recaptcha" data-sitekey="xxxxxxmyapikeyxxxxxxx_xxxxxxmyapikeyxxxxxxx"></div>
<li class="buttons">
<input type="hidden" name="form_id" value="1136056" />
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
</li>
</ul>
</form>
As far as I'm aware I have placed the code in the specified areas of my webpage. One before the closing tag on your HTML template and the snippet at the end of the where I want the reCAPTCHA widget to appear.
I have put the recaptcha before the submit button. There is a part about the server side integration that I do not understand.
[QUOTE]
When your users submit the form where you integrated reCAPTCHA, you'll
get as part of the payload a string with the name "g-recaptcha-response".
In order to check whether Google has verified that user,
send a POST request with these parameters:
URL: https://www.google.com/recaptcha/api/siteverify
secret (required) xxxxxmysecretkeyxxxxxxx
response (required) The value of 'g-recaptcha-response'.
remoteip The end user's ip address.
[/QUOTE]
Can anyone please shed some light on this please.
Thankyou
So we set up the form and make sure your library is included, I prevent the submit button from being clicked while the recaptcha has not been completed and show a tooltip to notify the user it is needed to continue. Then enable it when it has been complete using the callback methods.
login.php
<div class="formContainer">
<script src='https://www.google.com/recaptcha/api.js'></script>
<form action="loginHandler.php" method="post" name="login_form" id="loginForm" class="loginForm">
<h2>Login</h2>
<p><input type="text" required placeholder="Email" name="email"></p>
<p><input type="password" required placeholder="Password" name="password" id="password"></p>
<div class="g-recaptcha" data-callback="captcha_filled"
data-expired-callback="captcha_expired"
data-sitekey="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX">
</div>
<div>
<p class="show-tt" data-toggle="tooltip" title="Complete the reCAPTCHA to login." data-placement="bottom">
<input id="submitLogin" type="submit" value="Login">
</p>
</div>
</form>
</div>
<script>
//prevent submit and show tooltip until captch is complete.
var submit = false;
$("#submitLogin").prop('disabled', true);
function captcha_filled() {
submit = true;
$("#submitLogin").prop('disabled', false);
$(".show-tt").tooltip('destroy');
}
function captcha_expired() {
submit = false;
$("#submitLogin").prop('disabled', true);
showTooltip();
}
function showTooltip () {
$(".show-tt").tooltip('show');
}
</script>
Now we post to loginHandler.php, or wherever your form submits too and then there we will assign your secret key and then verify the request with google.
loginHandler.php
$secret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
if (isset($_POST["g-recaptcha-response"])) {
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secret) .
'&response=' . urlencode($_POST['g-recaptcha-response']) . '&remoteip=' . urlencode($_SERVER['REMOTE_ADDR']);
//ip address is optional
$result = json_decode(file_get_contents($url), true);
if ($result != null && $result['success'] === true) {
//success, handle login/submit data or whatever
} else {
//response is bad, handle the error
header('Location: login.php?error=4');
}
} else {
//captcha response is not set, handle error
header('Location: login.php?error=5');
}
I've a list of records and want to update one. When I click on one, it show a form with all input fields which are already populated using JsonRest. I've edited the fields and now I want to send it to server for updating.
How can I send an Object with dojo?
I tried like this, but at the controller side the value is null.
on(dom.byId("poolForm"), "submit", function(evt) {
var formObj = domForm.toObject("poolForm");
console.log(formObj);
request.post("/path/to/EditSubmit", {
data : formObj,
method : "POST"
}). then(function(data) {
console.log("data");
});
});
In spring I used:
public void editedForm(HttpServletResponse response, #RequestBody MyClass myClass) {
poolParam.getAdd();
}
Assuming you are creating a new record and not updating one, you can use method add(object, options) for your JsonRest.
Example:
require(["dojo/store/JsonRest"], function(JsonRest){
// your store
var store = new JsonRest({
target: "/some/resource"
});
// add an object passing an id
store.add({
foo: "foo"
}, {
id: 1
});
});
More informations can be found at JsonRest API and JsonRest guide.
EDIT:
As for your comment request, in case you would like to send an object using dojo/request/xhr instead of JsonRest, you can use the following example, basically:
Use dojo/dom-form utility, to get out values from your form. This utility function will return an object. More info here.
Use dojo/request/xhr to send via Ajax the object previously retrieved from dojo/dom-form, this is the data sent to the server. More info here.
Quick demo here:
https://jsbin.com/mocoxuhotu/edit?html,output
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link type="text/css" rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/dojo/1.10.0/dijit/themes/claro/claro.css">
<script data-dojo-config="async: 1" src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script>
<script>
require([
"dojo/query",
"dojo/dom-form",
"dojo/request/xhr",
"dijit/registry",
"dijit/form/Form",
"dojo/parser",
"dojo/domReady!"
], function (
query,
domForm,
xhr,
registry,
Form,
parser
) {
var form = new Form({}, 'myForm');
query("a.myLink").on("click", function () {
var data = domForm.toObject(form.domNode);
xhr.post("/echo/json", {
data: data // data to transfer
}).then(function () {
console.log("Success");
});
});
});
</script>
</head>
<body class="claro">
<form data-dojo-type="dijit/form/Form" id="myForm">
<fieldset>
<ul>
<li>
<label for="name">Name:</label>
<input type="text" name="name" />
</li>
<li>
<label for="firstname">First name:</label>
<input type="text" name="firstname" />
</li>
</ul>
</fieldset>
</form>
<a class="myLink">Submit the form</a>
</body>
</html>