Offline and Online syncing with Web applications in HTML5? - mysql

I have a basic web application below that has a sqlite storage measure implemented into it.
I would like it to be able to update my mysql server anytime it is connected, and store values to push to the database after it has lost connection. I would like it to be able to
use a timestamp comparison as a safety measure, just in case values on the server differ, we can to a stamp check to see if what it is trying to alter IS the most current values.
(this will be run from multiple computers, so will need SOME kind of failsafe).
I believe that this transaction WILL only need to be one way though, the values just need to update the server, values will not need to be passed back to the application, so we could technically destroy the database upon a real completion, or possibly perform a rollback if it breaks somewhere. Is this a doable thing, or am I really asking to much here?
Here's a very basic app I'd like to use as a model.
<!DOCTYPE html>
<html>
<head>
<title>Golf score keeper</title>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1.4.1");
</script>
<script>
var db = window.openDatabase("scores", "", "Previous Scores", 1024*1000);
function insertScore(hole_num, num_strokes, course_id, email) {
db.transaction(function(tx) {
tx.executeSql('INSERT INTO Strokes (course_id, hole_num, num_strokes, email) VALUES (?, ?, ?, ?)', [course_id, hole_num, num_strokes, email]);
});
}
function renderResults(tx, rs) {
e = $('#previous_scores');
e.html("");
for(var i=0; i < rs.rows.length; i++) {
r = rs.rows.item(i);
e.html(e.html() + 'id: ' + r['id'] + ', hole_num: ' + r['hole_num'] + ', num_strokes: ' + r['num_strokes'] + ', email: ' + r['email'] + '<br />');
}
}
function renderScores(email) {
db.transaction(function(tx) {
if (!(email === undefined)) {
tx.executeSql('SELECT * FROM Strokes WHERE email = ?', [email], renderResults);
} else {
tx.executeSql('SELECT * FROM Strokes', [], renderResults);
}
});
}
$(document).ready(function() {
db.transaction(function(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS Courses(id INTEGER PRIMARY KEY, name TEXT, latitude FLOAT, longitude FLOAT)', []);
tx.executeSql('CREATE TABLE IF NOT EXISTS Strokes(id INTEGER PRIMARY KEY, course_id INTEGER, hole_num INTEGER, num_strokes INTEGER, email TEXT)', []);
});
$('#score_form').submit(function() {
strokes = { 1: $('#hole1').val(), 2: $('#hole2').val() };
for (var hole_num in strokes) {
insertScore(hole_num, strokes[hole_num], 1, $('#email').val());
}
renderScores();
return false;
});
$('#filter_previous_scores_form').submit(function() {
e = $('#filter_by_email').val();
renderScores(e);
return false;
});
renderScores();
});
</script>
</head>
<body>
<form method="get" id="score_form">
<div>
<label for="1">Hole 1</label>
<input type="number" min="1" value="4" id="hole1" name="hole1" size="2" step="1" />
</div>
<div>
<label for="2">Hole 2</label>
<input type="number" min="1" value="4" id="hole1" name="hole2" size="2" step="1" />
</div>
<div>
<input type="email" id="email" placeholder="Enter your email address" size="40"/>
</div>
<div>
<input type="submit" value="Upload Score" />
</div>
</form>
<div>
<h2>Previous Scores</h2>
<form id="filter_previous_scores_form">
<input type="email" placeholder="Filter scores by email" size="40" id="filter_by_email" /><br />
<input type="submit" value="Filter" />
</form>
</div>
<div id="previous_scores">
</div>
</body>
</html>

You shoulg take a look at Ajax in a setInterval loop.

you can apply the logic of set interval when you found navigator.online=true then you can call ajax.

Related

Which input element that accept digits only and allows a limited number of characters

I am trying to implement an (zip code of my country) input field that only accept digits and limit the number of characters to 5.
Which html input type and attributes are more appropriate for this task ?
<input type="text" name="zipcode" pattern="[0-9]{5}" />
pattern="\d{5}" would also work. But make sure to re-check it in your target-script because form-elements can be manipulated.
A complete example (WITH JQUERY) for checking values on change or keyup in the .checkFieldNum values and on submit the form.
JS
function checkNum(value)
{
return value.match(/\d{5}/);
}
$(document).ready(function(){
// trigger if element-value with class="checkFieldNum" changes or key is pressed
$('.checkFieldNum').on('change keyup',function(event){
if(checkNum($(this).val()) === false)
{
$(this).css({background:'tomato'})
}
else
{
$(this).css({background:''})
}
})
// trigger if form should be submitted
$('.formClassForSubmit').on('submit',function(event){
event.preventDefault();
var goOn = true;
$('.checkFieldNum').each(function(){
if(checkNum($(this).val()) === false)
{
goOn = false;
alert($(this).attr('name') + ' has wrong value')
}
})
if(goOn === true)
{
// In this case, everything is OK and go on whatever you will do..
}
})
})
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="?" method="post" class="formClassForSubmit">
<input type="text" class="checkFieldNum" name="zipcode1" pattern="[0-9]{5}" />
<input type="text" class="checkFieldNum" name="zipcode2" pattern="\d{5}" />
<input type="submit" name="send" value="send" />
</form>
see https://jsfiddle.net/7hbj6a3e/3/
<input type="number" minlength="5" maxlength="5" name="zipcode" />
see https://www.w3schools.com/tags/tag_input.asp

Express.js not adding into mysql

I'm a beginner to ExpressJS, I want to be able to add records to the "site" table. However, when I run the following code, it says:
Error: ER_BAD_FIELD_ERROR: Unknown column 'BeastMode' in 'field list'.
"BeastMode" is an entry I made to the shortName field.
A little context: I'm not supposed to use ORM. I have to use raw sql queries to add to MYSQL database.I'm using 'mysql'package for Nodejs to connect to the database.
var squery = "INSERT INTO SITE (shortName,addressLine1,addressLine2,city,state,zipcode,phoneNumber) VALUES "+
"("+
req.body.shortName+", "+
req.body.addressLine1+", "+
req.body.addressLine2+", "+
req.body.city+", "+
req.body.state+", " +
req.body.zipcode+", " +
req.body.phoneNumber+" );"
console.log(req.body);
dbconnector.query(squery,function(err,rows,fields){
if(!err){
res.send("Record Added Successfully: "+req.body);
}else{
res.send("Error: "+ err);
}
});
});
Also, here is my dbconnect.js file:
var mysql = require('mysql');
dbconnect = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database:"rsacs"
});
module.exports = dbconnect
Here is my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<% include head %>
</head>
<body class="container">
<header>
<% include header %>
</header>
<main>
<div>
<h1><%=title%></h1>
<form method="post" action="/site/create" >
<div class="form-group">
<label for="shortName">Shortname</label>
<input type="text" class="form-control" placeholder="Shortname" name="shortName"><br>
<label for="Address Line 1"> Address Line 1:</label>
<input type="text" class="form-control" placeholder="Address Line 1" name="addressLine1"><br>
<label for="Address Line 2"> Address Line 2:</label>
<input type="text" class="form-control" placeholder="Address Line 2" name="addressLine2"><br>
<label for="City">City:</label>
<input type="text" class="form-control" placeholder="City" name="city"><br>
<label for="State">State:</label>
<input type="text" class="form-control" placeholder="State" name="state"><br>
<label for="Zipcode">Zipcode:</label>
<input type="text" class="form-control" placeholder="Zipcode" name="zipcode"><br>
<label for="PhoneNumber">Phone Number:</label>
<input type="text" class="form-control" placeholder="PhoneNumber" name="phoneNumber"><br>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</main>
<footer>
<% include footer %>
</footer>
</body>
</html>
Here is my Site table structure
To echo #AnshumanJaiswal's solution, you're probably encountering an escape character problem.
The solution I'm going to propose, though, is different. The mysql nodejs driver supports prepared queries. As such, the most robust way to sort your query is:
var squery = "INSERT INTO SITE (shortName,addressLine1,addressLine2,city,state,zipcode,phoneNumber) VALUES (?,?,?,?,?,?,?);
var objs = [req.body.shortName,req.body.addressLine1,req.body.addressLine2,req.body.city,req.body.state,req.body.zipcode,req.body.phoneNumber]
sql = mysql.format(squery, objs);
// now you have a properly-escaped SQL query which you can execute as usual:
connection.query(squery, objs, function (error, results, fields) {if (error) throw error;});
Let me know if this doesn't sort your problem.
the values are string and you are not passing them as string.
There are two possible ways:
Solution 1.
add `` to your string values like:
var squery = "INSERT INTO SITE (shortName,addressLine1,addressLine2,city,state,zipcode,phoneNumber) VALUES "+
"('"+
req.body.shortName+"', '"+
req.body.addressLine1+"', '"+
req.body.addressLine2+"', '"+
req.body.city+"', '"+
req.body.state+"', '" +
req.body.zipcode+"', " +
req.body.phoneNumber+" );"
...
Solution 2.
make an object from body data as:
var data = {
shortName: req.body.shortName,
addressLine1: req.body.addressLine1,
addressLine1: req.body.addressLine2,
city: req.body.city,
state: req.body.state,
zipcode: req.body.zipcode,
phoneNumber: req.body.phoneNumber
};
var squery = "INSERT INTO SITE SET ?";
dbconnector.query(squery, data, function(err,rows,fields){
if(!err){
console.log(rows);
res.send("Record Added Successfully.");
}else{
res.send("Error: "+ err);
}
});

Correctly using gumbo-parser to iterate and find the things I need?

I'm working on a pure C99 practising project which can do a login simulation for our school's CAS login system.
Now I'm trying to use Gumbo HTML parser to parse our school's login page. Here is the form section and I need to get the login ticket from it before I run the POST request to submit the form, which is the "hidden" type input element with name "lt". (i.e. line with <input type="hidden" name="lt" value="LT-000000-b4LktCXyzXyzXyzXyzXyzXyz" />, and I need to parse the "value").
I've wrote some code, but it seems cannot find out this input element. Here is my C program's function:
const char * parse_login_ticket_old(char * raw_html)
{
// Parse HTML into Gumbo memory structure
GumboOutput * gumbo_output = gumbo_parse(raw_html);
// Prepare the node
GumboNode * gumbo_root = gumbo_output->root;
assert(gumbo_root->type == GUMBO_NODE_ELEMENT);
assert(gumbo_root->v.element.children.length >= 2);
const GumboVector* root_children = &gumbo_root->v.element.children;
GumboNode* page_body = NULL;
for (int i = 0; i < root_children->length; ++i)
{
GumboNode* child = root_children->data[i];
if (child->type == GUMBO_NODE_ELEMENT && child->v.element.tag == GUMBO_TAG_BODY)
{
page_body = child;
break;
}
}
assert(page_body != NULL);
GumboVector* page_body_children = &page_body->v.element.children;
for (int i = 0; i < page_body_children->length; ++i)
{
GumboNode* child = page_body_children->data[i];
GumboAttribute * input_name_attr = gumbo_get_attribute(&child->v.element.attributes, "name");
if (child->type == GUMBO_NODE_ELEMENT && child->v.element.tag == GUMBO_TAG_INPUT && strcmp(input_name_attr->value, "lt") == 0)
{
GumboAttribute * input_value_attr = gumbo_get_attribute(&child->v.element.attributes, "value");
return input_name_attr->value;
}
}
return NULL;
}
In case someone need for debugging, here is a example of our schools page. Possible sensitive data has been removed.
<body>
<div id="wrapper">
<div id="contentArea" role="main">
<div class="form login" role="form">
<h2 class="hidden">Login</h2>
<form id="fm1" class="fm-v clearfix" action="/schoolcas/login?jsessionid=1234567890" method="post"><div class="formRow">
<label for="username" class="label">Student ID</label>
<div class="textBox">
<input id="username" name="username" class="schoolcas text" aria-required="true" type="text" value="" size="25" maxlength="25"/></div>
</div>
<div class="formRow">
<label for="password" class="label">Password</label>
<div class="textBox">
<input id="password" name="password" class="schoolcas text" aria-required="true" type="password" value="" size="25" autocomplete="off"/></div>
</div>
<div class="formRow">
<input type="hidden" name="lt" value="LT-000000-b4LktCXyzXyzXyzXyzXyzXyz" />
<input type="hidden" name="execution" value="e2s1" />
<input type="hidden" name="_eventId" value="submit" />
<input class="button grey submit" name="submit" value="Login" type="submit" />
</div>
</form>
</div>
</div>
</div>
</body>
Anyway, my program seems just stop at the top of the body element and it returns NULL later on.
So I would like to know how to do a correct search, and find out the input element I need?
I've figured it out by myself from the Google sample code (https://github.com/google/gumbo-parser/blob/master/examples/find_links.cc).
Here's the code. It's crappy but it works anyway.
const char * find_attribute(GumboNode * current_node, GumboTag element_tag_type,
char * element_term_key, char * element_term_value, char * desired_result_key)
{
const char * lt_token = NULL;
// Return NULL if it is in WHITESPACE
if (current_node->type != GUMBO_NODE_ELEMENT)
{
return NULL;
}
// Set the element's term key,
// e.g. if we need to find something like <input name="foobar"> then element search term key is "name",
// and element search value is "foobar"
GumboAttribute* lt_attr = gumbo_get_attribute(&current_node->v.element.attributes, element_term_key);
if (lt_attr != NULL && current_node->v.element.tag == element_tag_type && (strcmp(lt_attr->value, element_term_value) == 0))
{
lt_token = gumbo_get_attribute(&current_node->v.element.attributes, desired_result_key)->value;
return lt_token;
}
GumboVector* children = &current_node->v.element.children;
for (unsigned int i = 0; i < children->length; ++i)
{
lt_token = find_attribute(children->data[i], element_tag_type,
element_term_key, element_term_value, desired_result_key);
// Force stop and return if it gets a non-null result.
if(lt_token != NULL)
{
return lt_token;
}
}
}

HTML5 required attribute one of two fields

I have a form with two required input fields:
<form>
<input type="tel" name="telephone" required>
<input type="tel" name="mobile" required>
<input type="submit" value="Submit">
</form>
Is it possible to get browsers to validate so only one of them is required? i.e if telephone is filled, don't throw an error about mobile being empty and vice versa
Update 2020-06-21 (ES6):
Given that jQuery has become somewhat unfashionable in the JavaScript world and that ES6 provides some nice syntactic sugar, I have written a pure JS equivalent to the original answer:
document.addEventListener('DOMContentLoaded', function() {
const inputs = Array.from(
document.querySelectorAll('input[name=telephone], input[name=mobile]')
);
const inputListener = e => {
inputs
.filter(i => i !== e.target)
.forEach(i => (i.required = !e.target.value.length));
};
inputs.forEach(i => i.addEventListener('input', inputListener));
});
<form method="post">
Telephone:
<input type="tel" name="telephone" value="" required>
<br>Mobile:
<input type="tel" name="mobile" value="" required>
<br>
<input type="submit" value="Submit">
</form>
This uses the input event on both inputs, and when one is not empty it sets the required property of the other input to false.
Original Answer (jQuery):
I played around with some ideas and now have a working solution for this problem using jQuery:
jQuery(function ($) {
var $inputs = $('input[name=telephone],input[name=mobile]');
$inputs.on('input', function () {
// Set the required property of the other input to false if this input is not empty.
$inputs.not(this).prop('required', !$(this).val().length);
});
});
I've written a jQuery plugin wrapping the above JavaScript code so that it can be used on multiple groups of elements.
Based on Andy's answer, but I needed a checkbox implementation & came up with this.
what role(s) do you want?
<input type="checkbox" data-manyselect="roler" name="author" required>
<input type="checkbox" data-manyselect="roler" name="coder" required>
<input type="checkbox" data-manyselect="roler" name="teacher" required>
where will you work?
<input type="checkbox" data-manyselect="placement" name="library" required>
<input type="checkbox" data-manyselect="placement" name="home" required>
<input type="checkbox" data-manyselect="placement" name="office" required>
jQuery(function ($) {
// get anything with the data-manyselect
// you don't even have to name your group if only one group
var $group = $("[data-manyselect]");
$group.on('input', function () {
var group = $(this).data('manyselect');
// set required property of other inputs in group to false
var allInGroup = $('*[data-manyselect="'+group+'"]');
// Set the required property of the other input to false if this input is not empty.
var oneSet = true;
$(allInGroup).each(function(){
if ($(this).prop('checked'))
oneSet = false;
});
$(allInGroup).prop('required', oneSet)
});
});
Here for anyone else getting here by googling and wanting a quick solution for one of many checkboxes.
You would better do form data validation with Javascript anyway, because the HTML5 validation doesn't work in older browsers. Here is how:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Form Validation Phone Number</title>
</head>
<body>
<form name="myForm" action="data_handler.php">
<input type="tel" name="telephone">
<input type="tel" name="mobile">
<input type="button" value="Submit" onclick="validateAndSend()">
</form>
<script>
function validateAndSend() {
if (myForm.telephone.value == '' && myForm.mobile.value == '') {
alert('You have to enter at least one phone number.');
return false;
}
else {
myForm.submit();
}
}
</script>
</body>
</html>
.
Live demo here: http://codepen.io/anon/pen/LCpue?editors=100. Let me know if this works for you, if you will.
For two text fields #Andy's answer is working awesome, but in case of more than two fields we can use something like this.
jQuery(function ($) {
var $inputs = $('input[name=phone],input[name=mobile],input[name=email]');
$inputs.on('input', function () {
var total = $('input[name=phone]').val().length + $('input[name=mobile]').val().length + $('input[name=email]').val().length;
$inputs.not(this).prop('required', !total);
});
});

How to find duplicate id's in a form?

I've created a form with about 800 fields in it. Unknowingly I've given same id for few fields in the form. How to trace them?
The http://validator.w3.org/ will be the handy solution. But using jquery you can do something like this:
//See your console for duplicate ids
$('[id]').each(function(){
var id = $('[id="'+this.id+'"]');
if(id.length>1 && id[0]==this) {
console.log('Duplicate id '+this.id);
alert('duplicate found');
}
});
Hope this helps.
This might help you
Source: Finding duplicate ID’s on an HTML page
Finding duplicate ID’s on an HTML page
Written by Eneko Alonso on May 6, 2011
Looks like sometimes we forgot element ID’s
are meant to be unique on a HTML page. Here is a little bit of code I
just wrote to find duplicate ID’s on a page (run the code on your
browser’s javascript console):
var idList = {};
var nodes = document.getElementsByClassName('');
for (var i in nodes) {
if (!isNaN(i) && nodes[i].id) {
idList[nodes[i].id] = idList[nodes[i].id]? idList[nodes[i].id]+1:1;
}
}
for (var id in idList) {
if (idList[id] > 1) console.log("Duplicate id: #" + id);
}
I've created an example for you to have a look at, it finds all of the duplicate IDs within a form/element on a page and prints the duplicates ID names to the console.
The array contains method was taken from this post.
<html>
<body>
<form id="frm">
<input type="text" id="a" />
<input type="text" id="b" />
<input type="text" id="c" />
<input type="text" id="d" />
<input type="text" id="e" />
<input type="text" id="f" />
<input type="text" id="a" />
<input type="text" id="h" />
<input type="text" id="i" />
<input type="text" id="j" />
<input type="text" id="d" />
<input type="text" id="l" />
</form>
</body>
<script type="text/javascript">
Array.prototype.contains = function(obj) { //Add a 'contains' method to arrays
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
}
frm = document.getElementById('frm'); //Get the form
els = frm.getElementsByTagName('input'); //Get all inputs within the form
ids = new Array(els.length); //Create an array to hold the IDs
for(e = 0; e < els.length; e++) { //Loop through all of the elements
if(ids.contains(els[e].id)) //If teh array already contains the ID we are on
console.log('Duplicate: '+els[e].id); //Print 'Duplicate: {ID}' to the console
ids.push(els[e].id); //Add the ID to the array
}
</script>
</html>
The above code will output the following:
Duplicate: a
Duplicate: d
One-ish liner using just array methods:
[].map.call(document.querySelectorAll("[id]"),
function (e) {
return e.id;
}).filter(function(e,i,a) {
return ((a.lastIndexOf(e) !== i) && !console.log(e));
})
Logs every duplicate and returns an array containing the ids if any were found.
There is a Chrome extension named Dup-ID which if you install, you just need to press the button to check duplicated ids.
Link of install: https://chrome.google.com/webstore/detail/dup-id-scans-html-for-dup/nggpgolddgjmkjioagggmnmddbgedice
By defualt Notepad++ has syntax highlighting that if you double click one word to select it, it will highlight all other occurences of the same word. You are going to have to do some (probably a lot) of manual work renaming things, I mean since fields can't come up with their own unique name.