Transcript PPT

SPIFFY CLIENT-SIDE APIS
Going from good to great on the client
• Form validation
– Very simple validation
– Simple jQuery validation
– Slick validation with jQuery plugin
• Persistence
– Cookies
– Local storage
– Database
• APIs for your creative juices
– Geolocation
– Canvas
Form validation
• Validation = checking if data values are ok
• Crucial for security, reliability and usability
– Prevents users from…
• Putting evil data into your database
• Crashing your web page (e.g., using "Bob" as an int)
• Getting confused about why stuff doesn't work right
Validate inputs on the client & server
• Validation on the client
– Help the user to find and fix mistakes fast
• Validation on the server
– Help protect your database and web app
Web server
Browser
Validate
Validate
Ultra-simple client-side validation
<script>
function isValid(frm) {
var str = frm.myint.value;
var rv = /^\-?[0-9]+$/.test(str);
if (!rv) alert("myint should be an int.");
return rv;
}
</script>
<form onsubmit="return isValid(this)">
Enter an int: <input type="text" name="myint">
<input type="submit">
</form>
Simple validation with jQuery
<!DOCTYPE html>
<html><head><script src="jquery-1.8.2.min.js"></script></head><body>
<script>
function isValid(frm) {
var str = frm.myint.value;
var rv = /^\-?[0-9]+$/.test(str);
$("#err").text(rv ? "" : "myint should be an int.");
return rv;
}
</script>
<form onsubmit="return isValid(this)">
Enter an int: <input type="text" name="myint"><span id="err"></span>
<input type="submit">
</form>
</body></html>
Declarative validation with jQuery
<!DOCTYPE html>
<head>
<script src="jquery-1.8.2.min.js"></script>
<script src="jquery.validate.min.js"></script>
<script>
$(document).ready(function() {
$("#frm").validate();
});
</script>
</head>
<body>
<form id="frm">
Some text: <input class="required" name="mytext"><BR>
Some email: <input class="required email" name="myemail"><BR>
Some int: <input class="required digits" name="myint"><BR>
<input type="submit">
</form>
</body>
</html>
jquery.validate.js
•
Currently available from
– http://jqueryjs.googlecode.com/svn-history/r6243/trunk/plugins/validate/jquery.validate.js
•
Supported validation classes
–
–
–
–
–
–
–
–
–
–
–
–
–
–
required: This field is required
remote: Please fix this field
email: Please enter a valid email address
url: Please enter a valid URL
date: Please enter a valid date
number: Please enter a valid number
digits: Please enter only digits,
creditcard: Please enter a valid credit card number
equalTo: Please enter the same value again
accept: Please enter a value with a valid extension
maxlength: Max # characters allowed
minlength: Min # characters allowed
max: Max number value allowed
min: Min number value allowed
If you want to write your own jQuery
validation plugin, you may need these APIs
$("#elementid").val()
– Retrieves the value of some HTML form element
$("<span id='myspan'></span>").insertAfter("#elementid")
– Creates a span and inserts it after someNode
$("#elementid").bind('change', jsFunction);
– Registers jsFunction to be called on a change event, such as
function jsFunction() {alert($(this).text());}
$("#myspan").show() and .hide()
– Makes an element visible or invisible
$(".myclass").each(someFunction)
– Runs someFunction on each item in wrapped set
$("div.myclass").get(0)
– Gets the first actual DOM node (unwrapped) in the wrapped set
Persistence
• Data stored on the client side
– Provides a means for user-customization
– Eliminates the need to retrieve the data off server
– Facilitates off-line mode for web sites
• Options available to you
– Cookies; short strings, automatically copied to server
– Local storage: short strings, not automatically copied
– Database: structured data, not automatically copied
Persistence with cookies
• You can set a string and then retrieve it again
later on (e.g., when user reloads the page)
– You can control when the cookie expires.
• The strings will also automatically be included in
messages to servers in a specified domain
– That way, your server programs (e.g., PHP) also have
access to this data, automatically.
– Just as some browsers disallow AJAX calls to a file
system, browsers may "forget" cookies that are set by
HTML pages served from the file system.
Cookie example (use Firefox)
<!DOCTYPE html>
<head>
<script src="jquery-1.8.2.min.js"></script>
<script src="jquery.cookie.js"></script>
<script>
$(document).ready(function() {
var currentCount = $.cookie("countx");
var countAsNumber = parseFloat(currentCount);
countAsNumber = isNaN(countAsNumber) ? 1 : countAsNumber+1;
$.cookie("countx", countAsNumber, {expires: 365});
$("#counter").text(countAsNumber);
});
</script>
</head>
<body>
<div id="counter"></div>
</body>
</html>
Persistence with local data
• You can store data on the user's hard drive,
then retrieve it later on.
• Such data is not automatically sent to servers
– Which can be very nice from a security standpoint
– But note: As with cookies and client databases, all
local data is stored unencrypted.
localStorage example
<!DOCTYPE html>
<head>
<script src="jquery-1.8.2.min.js"></script>
<script>
$(document).ready(function() {
if (!window["localStorage"]) {
alert("No local storage. Should use cookie instead.");
} else {
var currentCount = localStorage["count"];
var countAsNumber = parseFloat(currentCount);
countAsNumber = isNaN(countAsNumber) ? 1 : countAsNumber+1;
localStorage["count"] = countAsNumber;
$("#counter").text(countAsNumber);
}
});
</script>
</head>
<body>
<div id="counter"></div>
</body>
</html>
Persistence with local database
• For a while it looked like we were going to get
standardized support for SQL on the client
– And some versions of some browsers even had an
implementation of this idea ("Web SQL")
– But all of their implementations used the same library
("sqlite") – everybody liked it.
– But the World Wide Web Consortium (W3C) requires
at least 2 differing implementations (i.e., not ok if
everybody likes same implementation?!)
– So now we are left without any standard that is widely
implemented
Local database, example?
• Haven't run across any examples yet that
follow standards and work properly in
multiple browsers, even from file system
• So:
– Stay tuned for the "indexedDB" standard
– Maybe even research it and use it for your How-To
APIs to get your creative juices flowing
• There are literally thousands of JavaScript
libraries (some standardized, some not)
• Examples
Geolocation
Canvas
Binary download
Video
Audio
Animation
Encryption
Compression
Drag and Drop
String formatting
Typography (as in fonts)
XML manipulation
Charting
Threads ("web workers")
File I/O
Types (as in JS with types)
Geolocation (use Firefox)
<!DOCTYPE html><html><head>
<script src="jquery-1.8.2.min.js"></script>
<script>
$(document).ready(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(callbackFunction);
} else {
alert("Not supported");
}
});
function callbackFunction(pos) {
$("#latlong").text("lat:"+pos.coords.latitude+";long:"+pos.coords.longitude);
}
</script>
</head>
<body><div id="latlong"></div></body>
</html>
Drawing pictures on canvas
<!DOCTYPE html><html><head>
<script src="jquery-1.8.2.min.js"></script>
<script>
$(function() {
var myCanvas = $("#canvas1").get(0);
var context = myCanvas.getContext("2d");
context.fillStyle = "#00ff00";
context.fillRect(10, 40, 100, 200); // x, y, width, height
context.strokeStyle = "#ff0000";
context.moveTo(200, 300); // x, y
context.lineTo(350, 350); // x, y
context.stroke();
});
</script></head><body>
<canvas id="canvas1" height="400" width="400" height="400"></canvas>
</body></html>
There's always more to learn
• For your How-To, consider covering a JS API
• For ideas, refer to
– http://diveintohtml5.info
– http://w3schools.com
– http://jquery.com
– http://developer.mozilla.org/
https://developer.mozilla.org/en-US/docs/JavaScript