How to submit form data to html5 local database - javascript

I am writing this very small application to run on an iPod. It is meant to store information based on a workout that I enter in. The storage will be html5 local database. My question is how do I get the information from the form which has multiple exercises and create a new record for each exercise? The html is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>lower</title>
<meta name="description" content="" />
<meta name="author" content="john" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script src="work.js" type="text/javascript" charset="utf-8"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<meta name="viewport" content="width=device-width; initial-scale=0.5; maximum-scale=0.6; minimum-scale=0.6; user-scalable=0;" />
</head>
<body>
<h1>Lower Body</h1>
<div>
<form method="post" id="workout_form">
<div>
<table id="hipadd">
<label for="hipAddReps">Hip Adductor</label>
<tr><td>Seat <input type="text" id="hipAddSeatSetting" size="1"/></td></tr>
<tr><td>Reps <input type="text" id="hipAddReps" size="2" value="10"/></td><td>Weight </td><td><input type="text" id="hipAddWeight" size="3" /></td></tr>
</table>
</div><br />
<div>
<table id="hipab">
<label for="hipAbReps">Hip Abductor</label>
<tr><td>Seat <input type="text" id="hipAbSeatSetting" size="1"/></td></tr>
<tr><td>Reps <input type="text" id="hipAbReps" size="2" value="10"/></td><td>Weight </td><td><input type="text" id="hipAbWeight" size="3"/></td></tr>
</table>
</div><br />
<div>
<table id="legcurl">
<label for="legCurlReps">Leg Curl</label>
<tr><td>Back <input type="text" id="legCurlBackSetting" size="1"/></td><td>Feet </td><td><input type="text" id="legCurlFeetSetting" size="1"/></td></tr>
<tr><td>Reps <input type="text" id="legCurlReps" size="2" value="10"/></td><td>Weight </td><td><input type="text" id="legCurlWeight" size="3"/></td></tr>
</table>
</div><br />
<div>
<table id="legext">
<label for="legExtensionReps">Leg Extension</label>
<tr><td>Back <input type="text" id="legExtensionBackSetting" size="1"/></td></tr>
<tr><td>Reps <input type="text" id="legExtensionReps" size="2" value="10"/></td><td>Weight </td><td><input type="text" id="legExtensionWeight" size="3"/></td></tr>
</table>
</div><br />
<div>
<table id="legpress">
<label for="legPressReps">Leg Press</label>
<tr><td>Back <input type="text" id="legPressBackSetting" size="1"/></td><td>Seat </td><td><input type="text" id="legPressSeatSetting" size="1"/></td></tr>
<tr><td>Reps <input type="text" id="legPressReps" size="2" value="10"/></td><td>Weight </td><td><input type="text" id="legPressWeight" size="3"/></td></tr>
</table>
</div><br />
<div>
<table id="glute">
<label for="gluteReps">Glute</label>
<tr><td>Seat <input type="text" id="gluteSeatSetting" size="1"/></td></tr>
<tr><td>Reps <input type="text" id="gluteReps" size="2" value="10"/></td><td>Weight </td><td><input type="text" id="gluteWeight" size="3"/></td></tr>
</table>
</div><br />
<div>
<button type="button" onclick="insertData()">Submit</button>
</div>
</form>
</div>
</body>
</html>
and the JavaScript I have so far is
$(function(){ initDatabase();
});
function initDatabase() {
try {
if (!window.openDatabase) {
alert('Local Databases are not supported by your browser.');
} else {
var shortName = 'WorkoutDB';
var version = '1.0';
var displayName = 'Workout Database';
var maxSize = 100000;
db = openDatabase(shortName, version, displayName, maxSize);
createTables();
}
} catch(e) {
if (e == 2) {
// Version mismatch.
console.log("Invalid database version.");
} else {
console.log("Unknown error "+ e +".");
}
return;
}
}
$(document).ready(function(){
db.transaction(function (transaction) {
//transaction.executeSql('drop table workout');
transaction.executeSql('CREATE TABLE IF NOT EXISTS workout(name TEXT, back TEXT, seat TEXT, feet TEXT, reps TEXT, weight TEXT);', [], nullDataHandler, errorHandler);
}
);
//insertData();
});
function insertData(){
var data = [$("label[for=hipAddReps]").text(), '', $('#hipAddSeatSetting').val(), '', $('#hipAddReps').val(), $('#hipAddWeight').val()];
db.transaction(function (transaction) {
transaction.executeSql("INSERT INTO Workout(Name, Back, Seat, Feet, Reps, Weight) VALUES (?, ?, ?, ?, ?, ?)", [data[0], data[1], data[2], data[3], data[4], data[5]]);
});
}
function errorHandler(transaction, error){
if (error.code==1){
// DB Table already exists
} else {
// Error is a human-readable string.
console.log('Oops. Error was '+error.message+' (Code '+error.code+')');
}
return false;
}
function nullDataHandler(){
console.log("SQL Query Succeeded");
}
so what I want is to fill in all of the fields on this form and hit the submit button at the bottom and have a new record inserted for each exercise I have.

Since you are going to make an application for the iOS (iPod), you would normally do this in objective C, however to do it in HTML5 you should look into a good framework. Take a look at Phonegap. They even have a getting started guide to get you up and running quickly. An alternative is appcelerator, although its not entirely free.
If you want to save form data to your phone you will need to consider using a light weight database, or flat file storage. Here is a link to phonegap's storage recommendations.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Contact Example</title>
<script type="text/javascript" charset="utf-8" src="phonegap-1.2.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//
function onDeviceReady() {
var db = window.openDatabase("test", "1.0", "Test DB", 1000000);
}
</script>
</head>
<body>
<h1>Example</h1>
<p>Open Database</p>
</body>
</html>
If you would like a great book about iphone, ipod and iOS development I would recommend Big Nerd Ranch's book, its a great first time book that walks you through all the red tape with apple's dev account setup.
Good luck, and I recommend re-posting your question with phonegap, and iOS tags to get more exposure.

Related

HTML Form cannot POST to JavaScript

Making a form in HTML where user input data and hit submit. Throws an error when the submitted.html file should load.
Cannot POST /api/submitted
The HTML on my index.html file is as follows:
<form action="/api/submitted" method="POST">
<fieldset class="fieldset">
<div>
<input type="text" name="fname" id="fname" placeholder="First Name" required><br>
<input type="text" name="lname" id="lname" placeholder="Last Name" required><br>
<input type="email" name="email" id="email" placeholder="Email" required><br>
<input type="tel" name="phone" id="phone" placeholder="Phone #" required><br>
</div>
<div>
In which campus are you interested?<br>
<select name="campus" id="" required>
<!-- options -->
<option value="">--Select--</option>
<option value="Towson">Towson</option>
<option value="Dundalk">Dundalk</option>
<option value="ChevyChase">Chevy Chase</option>
<option value="SilverSpring">Silver Spring</option>
</select><br>
</div>
<div>
About which workshop would you like to learn more?<br>
<input type="text" name="request" id="request"><br>
</div>
<div>
By submitting your information below, you agree to our
Terms of Use
and
Privacy Policy<br>
</div>
<div>
<button type="submit">Submit</button>
</div>
</fieldset>
</form>
And then my submitted.html text is:
<!DOCTYPE html>
<html lang="en">
<style type="text/css">#import url("css/submitted.css");</style>
<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>Submitted Form</title>
</head>
<body>
<header>
Thank you for your interest in our workshops! A member of our team will reach out soon!
</header><br><br>
<p>
Exit<br><br>
Return to form.
</p>
</body>
</html>
The JavaScript is as follows:
app.post('/api/submitted', async (req, res) => {
console.log('You posted from a form!');
console.log(req.body);
const data = { ...req.body, dateOfApplication: new Date() }; // ... copies whatever i have in an array and makes a deep copy
const collection = client.db("applications").collection("applicants");
try {
await collection.insertOne(data);
} catch (error) {
console.log(error.message);
}
res.status(201);
res.redirect('/submitted.html');
});
I am trying to get the input data stored onto a MongoDB server, and then that data can be viewed on a separate HTML file. Of course, the data is not being stored, too.
try to change form action to full end point api to be like this
http://localhost/api/submitted
the action you entered is a relative path the will redirect to
your_index_directory/api/submitted
try to use absolute path of full url as i mentioned before

Getting user input in HTML and then passing it into a JavaScript function

I'm trying to create a user input where the user can choose a stock Symbol, a Start Date, End Date and Interval. I would then like for this information to be passed along the javascript function api to retrieve information about that specific stock such as open, high, low, close, etc. The javascript function is working when I call the api function, but I'm not sure if I'm using the right code on HTML to use the user input and then passing this input onto the api() function on javascript once the user presses the "Execute" button
Javascript:
import yahooFinance from 'yahoo-finance2';
let symbolNew = document.getElementById("symbol").value;
let periodStart = document.getElementById("period1").value;
let periodEnd = document.getElementById("period2").value;
let intervalNew = document.getElementById("interval").value;
async function api(symbol, start, end, val) {
const query = String(symbol);
const queryOptions = { period1: new Date(start), period2: new Date(end), interval: String(val) };
let result = await yahooFinance.historical(query, queryOptions);
let resultWithSymbol = result.map((item) => ({ ...item, symbol: query })); //... is called the spread operator - it concatonates things
console.log(resultWithSymbol);
return resultWithSymbol;
};
api(symbolNew, periodStart, periodEnd, intervalNew);
HTML:
<!DOCTYPE html><p>API</p>
<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">
<script type="module" src="../dist/bundle.js"></script>
<title>Document</title>
</head>
<body>
<div class="symbol">
<p id="symbol"></p>
<label for="name">Symbol (4 characters):</label>
<input type="text" id="symbol" name="symbol" required
minlength="4" maxlength="4" size="10" placeholder="Exemplo: TSLA">
</div>
<div class="interval">
<label for="name">Interval: (1d, 1wk or 1mo):</label>
<input type="text" id="interval" name="interval" required
minlength="2" maxlength="3" size="10" placeholder="Exemplo: 1d">
</div>
<div class="period1">
<label for="name">Start Date:</label>
<input type="text" id="period1" name="period1" required
minlength="10" maxlength="10" size="20" placeholder="Exemplo: 2021-08-20">
</div>
<div class="period2">
<label for="name">End Date:</label>
<input type="text" id="period2" name="period2" required
minlength="10" maxlength="10" size="20" placeholder="Exemplo: 2021-08-25">
</div>
<div class="button">
<input type="button" name="buttonExecute" value="Execute" onclick="api(document.getElementById('symbol'),document.getElementById('period1'),document.getElementById('period2'),document.getElementById('interval'))"></input>
</div>
</body>
</html>
I'm aware that Node js doesn't recogniz "document." so I'll be using Webpack or Bable to get the input of the api() function onto the HTML
Thank you in advance
'value' (document.getElementById('symbol').value;) is missing in the HTML onclick event.

Can't link java into html/html file not replacing text

I have an html and javascript files
function saved() {
"use strict";
var description;
description = document.getElementById("description").value;
}
function savedd() {
"use strict";
var due_date;
due_date = document.getElementById("due_date").value;
}
function saverd() {
"use strict";
var reminder_date = document.getElementById("reminder_date").value;
}
document.getElementsByClassName("result").innerHTML = "My new text!";
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<meta name="viewport" content="user-scalable=no, initial-scale=.5, maximum-scale=1, minimum-scale=1, width=device-width" />
</head>
<body>
<div style="margin:0 auto;text-align:center">
<!-- Div align in the middle -->
<div style="margin-left:auto;margin-right:auto;text-align:center">
<form>
Description:<br>
<input type="text" name="description" onchange="saved()"><br>
<br>
<br>
Due Date:<br>
<input type="date" name="due_date" onchange="savedd()" ><br>
<br>
<br>
Reminder Date: <br>
<input type="text" name="reminder_date" onchange="saverd()"><br>
</form>
</div>
<div class="result"> PlaceHolder</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type='text/javascript' src="editpage.js"></script>
</body>
</html>
I want it to eventually replace the PlaceHolder text with the Description stored data so that I know that that part of the script is working properly so I can call on it later, but now it just sticks to saying PlaceHolder
Change getElementsByClassName("result") to getElementsByClassName("result")[0]. Your original call returns a collection of nodes, you want to set the innerHTML on a specific node.
Here's a fixed version of your snippet:
document.getElementsByClassName("result")[0].innerHTML = "My new text!";
<div style="margin:0 auto;text-align:center">
<!-- Div align in the middle -->
<div style="margin-left:auto;margin-right:auto;text-align:center">
<form>
Description:
<br>
<input type="text" name="description" onchange="saved()">
<br>
<br>
<br>Due Date:
<br>
<input type="date" name="due_date" onchange="savedd()">
<br>
<br>
<br>Reminder Date:
<br>
<input type="text" name="reminder_date" onchange="saverd()">
<br>
</form>
</div>
<div class="result">PlaceHolder</div>
</div>

Javascript Code isn't submitting to Parse

I am creating an app to send an object to a class in Parse, but the data in the form is being passed and nothing happens. I can submit data directly from the function showAlert, but no alert appears after setNotification and and showALert is used. Here is my code:
<!doctype html>
<head>
<meta charset="utf-8">
<title>My Parse App</title>
<meta name="description" content="My Parse App">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/styles.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.18.min.js"></script>
</head>
<body>
<div id="main">
<h1>You're ready to use Parse!</h1>
<p>Read the documentation and start building your JavaScript app:</p>
<ul>
<li>Parse JavaScript Guide</li>
<li>Parse JavaScript API Documentation</li>
</ul>
<div style="display:none" class="error">
Looks like there was a problem saving the test object. Make sure you've set your application ID and javascript key correctly in the call to <code>Parse.initialize</code> in this file.
</div>
<div style="display:none" class="success">
<p>You're message has now been submited.'</p>
</div>
</div>
<div class="login">
<form class="login-form" name="login-form">
<h2>Compose Message</h2>
<input type="text" name="school" id="school" placeholder="School Code" />
<p> </p>
<input type="text" name="name" id="name" placeholder="Name" />
<p> </p>
<input type="text" name="password" id="password" placeholder="Message" />
<p> </p>
<input type="button" value="Set Notification" onClick="setMessage();">
<p> </p>
<input type="button" value="Send Notification" onClick="showAlert();">
</form>
</div>
<script type="text/javascript">
function setMessage (){
var textField = form.school.value
var textField1 = form.name.value
var textField2 = form.password.value
}
function showAlert() {
Parse.initialize("appkey", "javascript key");
var TestObject = Parse.Object.extend(textField);
var testObject = new TestObject();
testObject.save({teacher: textField1), message:textField2)}, {
success: function(object) {
$(".success").show();
alert('The Message has been sent!');
},
error: function(model, error) {
$(".error").show();
alert('There has been an error.');
}
});
}
</script>
</body>
</html>
I am dusting off my Javascript knowledge to create an page that syncs to an iOS app. Any help is greatly appreciated!

dynamic javascript/php form with radios creating a second field

I'm having a little 'teething' problem here is my code so far
<form name="job_app">
Source?<br/>
<input type="radio" name="source" value="GAZ" id="GAZ" /> Stonoway Gazette <br/>
<input type="radio" name="source" value="JCP" id="JCP" /> Job Center <br/>
<input type="radio" name="source" value="WOM" id="WOM" /> Word of Mouth <br/><br/>
<script language="text/JavaScript">
if (document.job_app.source.GAZ.checked){
document.write='Issue <br/><input type="text" name="issue" /><br/><br/>';
}
else if (document.job_app.source.JCP.checked){
document.write='Ref <br/><input type="text" name="ref" /><br/><br/>';
}
//word of mouth has no additional input so there is no if statement for it
</script>
</form>
what i want this to do is create (or unhide) the issue or ref text box depending on which radio button is selected without creating multiple text boxes.
sorry for any inconvenience if this is a rookie mistake, i have never worked with java before nor a language like it.
This is the working code as of 07:15 26/05/2012 as thanks to Amy McCrobie.
It has undergone some edits since Amy's version (see below) i have moved all scripts above the form to make adding the next few fields easier, added a statement for word of mouth, omitted <head> as that is part of index.php and meta.php while this is for form.php, added a spacer and made the function name more specific.
index.php
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<?php
include './meta.php';
?>
</head>
<?php
/*if(isset($_POST['submit'])){
include './submit.php';
}
else{*/
include './form.php';
//}
?>
</html>
meta.php
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />
<meta http-Equiv="Cache-Control" Content="no-cache" />
<meta http-Equiv="Pragma" Content="no-cache" />
<meta http-Equiv="Expires" Content="0" />
<title>job_app</title>
<link rel="StyleSheet" type="text/css" href="./style.css"/>
form.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#issueEl").hide();
$("#refEl").hide();
});
function showHide_source(){
if (document.getElementById('GAZ').checked)
{
document.getElementById('issueEl').style.display = 'block';
document.getElementById('refEl').style.display = 'none';
document.getElementById('src_spEl').style.display = 'none';
}
if (document.getElementById('JCP').checked)
{
document.getElementById('issueEl').style.display = 'none';
document.getElementById('refEl').style.display = 'block';
document.getElementById('src_spEl').style.display = 'none';
}
if (document.getElementById('WOM').checked)
{
document.getElementById('issueEl').style.display = 'none';
document.getElementById('refEl').style.display = 'none';
document.getElementById('src_spEl').style.display = 'block';
}
}
</script>
<form name="job_app" action="" method="post">
Source?<br/>
<input type="radio" name="source" value="GAZ" id="GAZ" onChange="showHide_source()" /> Stonoway Gazette <br/>
<input type="radio" name="source" value="JCP" id="JCP" onChange="showHide_source()" /> Job Center <br/>
<input type="radio" name="source" value="WOM" id="WOM" onChange="showHide_source()" /> Word of Mouth <br/><br/>
<div class="hideable" id="issueEl">Issue <br/><input type="text" name="issue" /><br/><br/></div>
<div class="hideable" id="refEl">Ref <br/><input type="text" name="ref" /><br/><br/></div>
<div class="hideable" id="src_spEl"></div>
rest of form
<input...
.../>
</form>
style.css
div.hideable{
height: 62px;
}
Try this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<meta http-Equiv="Cache-Control" Content="no-cache">
<meta http-Equiv="Pragma" Content="no-cache">
<meta http-Equiv="Expires" Content="0">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#issueEl").hide();
$("#refEl").hide();
});
</script>
<title>Test</title>
</head>
<body>
<form name="job_app" action="" method="post">
Source?<br/>
<input type="radio" name="source" value="GAZ" id="GAZ" onChange="showHide()" /> Stonoway Gazette <br/>
<input type="radio" name="source" value="JCP" id="JCP" onChange="showHide()" /> Job Center <br/>
<input type="radio" name="source" value="WOM" id="WOM" onChange="showHide()" /> Word of Mouth <br/><br/>
<div id="issueEl">Issue <br/><input type="text" name="issue" /><br/><br/></div>
<div id="refEl">Issue <br/><input type="text" name="ref" /><br/><br/></div>
</form>
<script type="text/javascript">
function showHide(){
if (document.getElementById('GAZ').checked)
{
document.getElementById('issueEl').style.display = 'block';
document.getElementById('refEl').style.display = 'none';
}
if (document.getElementById('JCP').checked)
{
document.getElementById('issueEl').style.display = 'none';
document.getElementById('refEl').style.display = 'block';
}
}
</script>
</body>
</html>
I would suggest jQuery, it's not hard to learn, in fact I find it much easier than basic javascript
also I would go the route of two textboxes that are hidden, and then showing them via jQuery
as it stands now I think if the user checks one radio button and then the other two text boxes will appear
and with jQuery added (which is as easy as including the sript at the top of your page your code would be more like this...
<form name="job_app">
Source?<br/>
<input id="GAZ" type="radio" name="source" value="GAZ" id="GAZ" /> Stonoway Gazette <br/>
<input id="JCP" type="radio" name="source" value="JCP" id="JCP" /> Job Center <br/>
<input id="WOM" type="radio" name="source" value="WOM" id="WOM" /> Word of Mouth <br/><br/>
Issue <br/><input id="issue" type="text" name="issue" /><br/><br/>
Issue <br/><input id="ref" type="text" name="ref" /><br/><br/>
<script language="text/JavaScript">
$("#issue").css("display","none");
$("#ref").css("display","none");
if ($("#GAZ").checked){
$("#issue").css("display","inline");
$("#ref").css("display","none");
}
if ($("#JCP").checked){
$("#issue").css("display","none");
$("#ref").css("display","inline");
}
//word of mouth has no additional input so there is no if statement for it
</script>
</form>

Categories