How to create a Tableless Form.
Tableless design is one of the good practices to follow , using tables in forms might not be so harmful for CSS redesign sometimes, but you rather change the CSS styles instead of the structure.
<html>
<head></head>
<body>
<form>
<div class="row">
<div class="label cell"> Name : </div>
<div class="input cell">
<input type="text" name="name" />
</div>
</div>
<div class="row">
<div class="label cell"> Last Name: </div>
<div class="input cell">
<input type="text" name="lastname" />
</div>
</div>
<div class="row">
<div class="label cell">Email: </div>
<div class="input cell">
<input type="text" name="email" />
</div>
</div>
<div class="row">
<div class="label cell">Password: </div>
<div class="input cell">
<input type="password" name="password" />
</div>
</div>
<div class="row">
<div class="label cell">
</div>
<div class="input cell">
<button>Submit</button>
</div>
</div>
</form>
</body>
</html>
CSS:
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
font-weight: 300;
color: #2f2f2e;
}
form .row {
overflow: hidden;
border-top: 1px solid gray;
}
form .row .cell{
width: 300px;
overflow: hidden;
float: left;
padding-top: 5px;
padding-bottom: 5px;
}
form .row .label {
text-align: right;
margin-right: 2px;
}
form .row .input input[type='text'],input[type='password']{
height: 18px;
width: 200px;
border: 1px solid #b9b7ad;{
}
Tip of the day : Undeclared Variables
//Variable declaration
//Every declaration out of any scope becomes
//part of the global object like
var i = 0;
var j = 0;
var bar = function () {};
// A common JavaScript bug is with the undecleared variables in any scope they become part of the global object
function kiss() {
// anti-pattern ↓
// How many kisses you want?
k = 2;
return k;
}
kiss(); // <----- Returns the number a defined number of kisses
// oh look is part of the global object !!
console.log(k);
console.log(this.k);
console.log(window.k); // window is reference to the global object in the browser environment.
function kissMe () {
// anti-pattern ↓
for (k = 0; k < 10000000; k++) {
kiss();
}
return "My job is done here";
}
kissMe(); // <----- Ask for kisses 10000000 times.
// Opps we're stuck with infinite kisses :( we are dead now next time declare your variables like this
function kiss() {
var k = 2; // How many kisses mom gave you ?
return k;
}
function kissMe () {
for (var k = 0; k < 10000000; k++) {
kiss();
}
return "My job is done here";
}
kissMe ();
DOM Methods vs innerHTML
Finding a fast way to create elements, every browser works differently and this can make some simple tasks fast or slow, I find sometimes a hard dilema using innerHTML I know is easy and lazy for programmers in the other hand the DOM methods such a createElement, appendChild, createTextNode are elegant, understandable but is just to much code for a small piece of HTML maybe templating your HTML would be better.
Anyway I did some speed tests with the following code (you should try it).
var timer = 0,
endTimer = 0,
iterations = 100000,
i = 0;
//DOM Methods
var ul = document.createElement('ul')
timer = +new Date;
while (i < iterations ) {
var
li_1 = document.createElement('li'),
li_2 = document.createElement('li'),
li_3 = document.createElement('li'),
li_4 = document.createElement('li');
ul.appendChild(li_1);
ul.appendChild(li_2);
ul.appendChild(li_3);
ul.appendChild(li_4);
i++;
}
endTimer = (+new Date) - timer;
console.log(endTimer);
//innerHTML
i = 0;
timer = 0;
endTimer = 0;
var ul = document.createElement('ul');
timer = +new Date;
while (i < iterations ) {
ul.innerHTML ="<li></li><li></li><li></li><li></li>";
i++;
}
endTimer = (+new Date) - timer;
console.log(endTimer);
}());
//Chrome
690 ms //Dom Methods
1577 ms //innerHTML
//Opera
1930 ms //Dom Methods
1819 ms //innerHTML
//Firefox
538 ms //Dom Methods
3300 ms //innerHTML
//Safari
782 ms //DOM Methods
722 ms //innerHTML
JSPERF TESTS
http://jsperf.com/innerhtml-vs-createelement-appendchild
After few days testing DOM Methods speed WINS, but the code is just to big so we need to use a js minifier like
http://www.crockford.com/javascript/jsmin.html
http://jscompress.com/
to reduce your script size and speed up the download.
I'm currently working in a simple tool that converts your HTML string to DOM Methods but it just work in the browser I'm taking advantage of the browser DOM parser, I guess I'll require a DOM Parser if I want to run it in another environment, you can check it here.
http://labs.ramonlechuga.com/DOMMethodfy/
Source:
https://github.com/alejandrolechuga/DOMMethodfy
Checking object properties
When I'm working with an object and I need to check a property, I cannot go straight up I always first check if this one exists, but we have different ways to check them, before I used to do this.
//exists
console.log(object.property);
}
It works when the property is undefined, but if the property has false ,zero(0), or empty string ("") it wont work as we wanted.
Other way is checking if it has its own property by using
//exists
console.log(object.property);
}
But here you are just checking the properties that come with the object, not the ones that are inherited by the prototype chain. So in case you want to check all the properties use this code.
//exists
console.log(object.property);
}
It's really annoying checking long objects structures
data: {
item: {
sub_item: {
bla: {
here : {
iam: true
}
}
}
}
}
};
// This could throw us a Reference Error
if (data.item.sub_item.bla.here.iam) {
//it works
}
//Other way could be...
if (data)
if ("item" in data)
if ("sub_item" in data.item)
if ("bla" in data.item.sub_item)
if ("here" in data.item.sub_item.bla) {
//don't do this
}
Try this snippet:
var scope = thisObj || window;
for ( var i=0, j=this.length; i < j; ++i ) {
if ( fn.call(scope, this[i], i, this) ) {
return true;
}
}
return false;
};
function isSet (object, string) {
if (!object) return false;
var childs = string.split('.');
if (childs.length > 0 ) {
return !childs.some(function (item) {
if (item in object) {
object = object[item];
return false;
} else return true;
});
} else if (string in object) {
return true;
} else return false;
}
var object = {
data: {
item: {
sub_item: {
bla: {
here : {
iam: true
}
}
}
}
}
};
console.log(isSet(object,'data.item')); // true
console.log(isSet(object,'x')); // false
console.log(isSet(object,'data.item')); // true
console.log(isSet(object,'data.item.sub_item.bla.here.iam')); // true
Private & public properties for JavaScript
Here we have a good article about keeping private properties in your JavaScript kinda Java , well we know that JavaScript is not enough good for Object Orientation but it has a lot good parts
is very flexible.
Here we have the normal way for making "Classes"
//this is like the constructor
};
myClass.prototype.myMethod = function () {
//wow a method :D
};
var myClassInstance = new myClass();
Well we know that everybody who use firebug or javascript pretty often could have access to this objects, so a good way for keep this objects not accesible to the window parent object.. is doing this
var myClass = function () {
//this is like the constructor
};
myClass.prototype.myMethod = function () {
//wow a method :D
};
var myClassInstance = new myClass();
});
And this way is to keep your properties private even from your own objects (I took this method from the Douglas Crockford website), the problem here is that you just access from public to private properties, and private don't have access to public.
function privateMethod() {
alert("Hello I'm the private method");
}
return {
variable:1,
method: function () {
alert(this.variable); // shows 1
},
methodCallPrivate: function () {
privateMethod();
}
}
});
var myClassInstance = new myClass();
myClassInstance.method(); // shows 1
myClassInstance.methodCallPrivate(); //shows "Hello I'm the private method"
But I found this way if you want both have access to each other
var _public = {};
var _private = {};
_public.pubVariable = "Hello World from _public.pubVariable";
_private.priVariable = "Hello World from _private.priVariable";
_public.pubMethod= function() {
alert(_private.priVariable);
};
_private.priMethod = function() {
alert(_public.pubVariable);
};
_public.callpriMethod = function() {
_private.priMethod();
};
return _public;
});
var myClassInstance = new myClass();
myClassInstance.pubMethod(); // shows "Hello World from _private.priVariable"
myClassInstance.callpriMethod(); // shows "Hello World from _private.priVariable"
myClassInstance.priMethod(); //Throws an Error
PHP Error Handler, Tracking you project bugs
There’s a way to hide those ugly error outputs from PHP, and not just that you can track them, log them and manage them.
We have different type of errors some of them are possible to catch and others aren’t, in this post you will learn how to build your own error tracker, but first lets learn something about PHP errors, check the different type of errors in the following list.
| Value | Constant | Description | PHP |
| 1 | E_ERROR | Fatal run-time errors. Errors that cannot be recovered from. Execution of the script is halted | |
| 2 | E_WARNING | Non-fatal run-time errors. Execution of the script is not halted | |
| 4 | E_PARSE | Compile-time parse errors. Parse errors should only be generated by the parser | |
| 8 | E_NOTICE | Run-time notices. The script found something that might be an error, but could also happen when running a script normally | |
| 16 | E_CORE_ERROR | Fatal errors at PHP startup. This is like an E_ERROR in the PHP core | 4 |
| 32 | E_CORE_WARNING | Non-fatal errors at PHP startup. This is like an E_WARNING in the PHP core | 4 |
| 64 | E_COMPILE_ERROR | Fatal compile-time errors. This is like an E_ERROR generated by the Zend Scripting Engine | 4 |
| 128 | E_COMPILE_WARNING | Non-fatal compile-time errors. This is like an E_WARNING generated by the Zend Scripting Engine | 4 |
| 256 | E_USER_ERROR | Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error() | 4 |
| 512 | E_USER_WARNING | Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error() | 4 |
| 1024 | E_USER_NOTICE | User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error() | 4 |
| 2048 | E_STRICT | Run-time notices. PHP suggest changes to your code to help interoperability and compatibility of the code | 5 |
| 4096 | E_RECOVERABLE_ERROR | Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler()) | 5 |
| 6143 | E_ALL | All errors and warnings, except of level E_STRICT | 5 |
The error_reporting function has a parameter to set which type of error you want to show.
You can set to 0 if you don’t want to show nothing
To show the common errors
If you’re picky , this will help you to code better
This is the default set from php.ini
This show everything
I use this, I care more about these ones
You need to create a new PHP file that's going to handle the errors and you have to load it in every PHP file that runs by itself I mean that is not loaded in another PHP (but don't worry using require_once it will be loaded just once)...but well this depends of the structure of your project .
require_once('error_handler.php');
There's a function called set_error_handler with this one you can catch many errors but there are some E_FATAL errors that are impossible to catch with this function, so theres a trick to catch them and show something else instead.
1 2 3 4 5 6 7 8 | ini_set('display_errors', 'On'); #here we are setting our normal error handler set_error_handler('errorHandler'); #here we wrap the the error in tags ini_set('error_prepend_string', '<phpfatalerror>'); ini_set('error_append_string', '</phpfatalerror>'); #and all the output will pass through here our fatal error handler ob_start('fatalErrorHandler'); |
So in your function you should classified which kind of error you are receiving
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | function errorHandler($error_number, $error_string, $error_file, $error_line, $error_context) { $error_title = ""; $error_array = array(); $backtrace = array(); switch ($error_number) { case E_FATAL: $error_title = "Fatal Error"; break; case E_ERROR: $error_title = "Error"; break; case E_WARNING: $error_title = "Warning"; break; case E_PARSE: $error_title = "Parse Error"; break; case E_NOTICE: $error_title = "Notice"; break; case E_CORE_ERROR: $error_title = "Core Error"; break; case E_CORE_WARNING: $error_title = "Core Warning"; break; case E_COMPILE_ERROR: $error_title = "Compile Error"; break; case E_COMPILE_WARNING: $error_title = "Compile Warning"; break; case E_USER_ERROR: $error_title = "User Error"; break; case E_USER_WARNING: $error_title = "User Warning"; break; case E_USER_NOTICE: $error_title = "User Notice"; break; case E_STRICT: $error_title = "Strict Notice"; break; case E_RECOVERABLE_ERROR: $error_title = "Recoverable Error"; break; default: $error_title = "Unknown error ($error_number)"; break; } //Here you code to track errors } |
With this code from above you can send emails or log errors in Data Base.
The second function you need is the one it takes the fatal errors from the tags, and we show a custom error html.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | function fatalErrorHandler($bufferContent) { define('E_FATAL', 'efatal'); $output = $bufferContent; $matches = array(); $errors = ""; if ( preg_match('|<phpfatalerror>.*</phpfatalerror>|s', $output, &$matches) ) { foreach ($matches as $match) { $errors .= strip_tags($match) . "\n\n---\n\n"; } $var = errorHandler('efatal', 'Fatal Error', 'unknown', 'unknown', $errors); $filename = HTML_DIR . "unavailable.html"; $handle = fopen($filename, "r"); $contents = fread($handle, filesize($filename)); fclose($handle); $output = $contents; } return $var; } |
Well if you use this code I fully recommend you to take all the possible variables that might be part of the error.
There's a function call debug_backtrace that returns you the array of all the trace you code did. so I recommend you log it too.
Update: If you are using the PHP version 5.3 or earlier, now comes with the new error levels E_DEPRECATED & E_USER_DEPRECATED
Form submit like AJAX style using an Iframe
I remember the first time I start using AJAX it was really really amazing
till I found that I can't send images just text, well I'll show how to upload a file without refreshing the whole page.
Here is you html form code:
1 2 3 4 | <form enctype="multipart/form-data" method="post" > <input name="image" type="file" /> <input type="submit" value="Submit" /> </form> |
And you have add an Iframe element , doesn't matter in which part of the document but I recommend you put it inside of the form like this, add the target attribute to the form element and put the iframe name attribute as a target, you can hide the iframe with the style display:none.
1 2 3 4 5 | <form enctype="multipart/form-data" method="post" target="iframe"> <input name="image" type="file" /> <input type="submit" value="Submit" /> <iframe id="iframe" style="display:none"></iframe> </form> |
Ok the problem is that there's no way to fire the onload event of the iframe (I already tried many ways, and asked many people if you know how please let me know) so you have to do a Script that notice you when the Iframe is ready and not just that, maybe you'll need a response from the server.
So here we have to find a way to receive the data and call back a function when the iframe is loaded.
You can follow this way:
1 2 3 4 5 6 7 8 9 10 11 12 | <form action="submitIframe.php" enctype="multipart/form-data" method="post" target="iframe"> <input name="image" type="file" /> <input type="submit" value="Submit" /> <iframe name="iframe" style="display:none;"></iframe> </form> <script> function myCallBackFunction(data) { //put your code here alert(data); } </script> |
So you need to response something like this:
1 2 3 4 | <script type="text/javascript"> var data = "<?=$myServerResponse ?>"; parent.myCallBackFunction(data); </script> |
In this case I did it with PHP, this is going to be called within the iframe.
Welcome to my new blog
Hello readers, welcome to my new blog. The main reason I created because I want to share & save all the stuff I've learnt about building websites.
I'm going to post good tricks for the following languages:
JavaScript ( AJAX/DHTML)
PHP (OOP/MVC)
HTML/CSS
Flash & Flex
So welcome to anyone who comes along here. Please let me know if I have some mistakes on my posts
Thanks,
Ramon
