Saturday, October 22, 2011

All new HTML- HTML5

HTML 5 has come up with some super cool tags, which makes things(coding) easier and reduces the use of third party applications(flash, Adobe is going to launch Adobe Edge in near future which generates code in jQuery, HTML 5, CSS). Here are some of the tags which are revolutionary.

iframe: It is not related to Steve Jobs or Apple at all! ;) Well it is super awesome tag. It works like page in some page. Place it where ever you want. Try it, you gonna love it.
Syntax: <iframe src="somefile.html">Not supported by browser</iframe>

audio: Before this we used to use third party tools for audio. This lets you embed audio without any problem in your webpage.
Syntax: <audio controls="controls"><source src="somefile.mp3" type="audio/mp3" />Not supported by webbrowser</audio>

video: Same as audio just the tag name is changed and source type.
Syntax: <video controls="controls"><source src="somefile.mp4" type="audio/mp4" />Not supported by webbrowser</audio>

progress: Many times we brainstorm over progress bar. Here it is, very simple to use and looks pretty cool, basically dependent on OS you are using.
syntax: <progress value="40" max="100"></progress>

header: This creates header and it knows where it should be.
syntax: <header><p>Some thing some thing</p></header>

footer: This places footer in the webpage. But personally I don't understand its behaviour.
syntax: <footer>Some thing</footer>

nav: Now you don't need to write extra CSS for making navgation, like inline.
syntax: <nav><a href="1.html">One</a><a href="2.html">Two</a></nav>
Tip: Use nav with header and footer.

localStorage: HTML 5 also worked towards replacement of cookies. This stores data on client computer just as cookies but you can store large amount of data. Because whatever is needed can be fetched alone. It requires javascript to work.
syntax: <script type="text/javascript">localStorage.name = 'James Bond'</script>

sessionStorage: This is just like session but again created by javascript. It is also cool thing as you can understand.
syntax: <script type="text/javascript">sessionStorage.name = 'James Bond'</script>

canvas: This is the ultimate thing of all. You can draw on your web page now using this element. This works just as canvas in real but coding part. It has some easy calling involved for making lines, rectangle and other. This also uses javascript to create. Go on google HTML 5 games. You can create wonder using this. But first of all you need to read all about it.
syntax: <canvas id="mycanvas"></canvas>

Note: This is not all read about these tags, they have lot of things.
          You can see dive into HTML 5. Everything is explained beautifully.

Creating HTML elements dynamically

There are times when we want to create HTML elements on the page, result of a certain action. Below is explained how to do that using Javascript.
I have written a javascript which you can download. Please read "README" before using it.

Required: Javascript, HTML.

Using:
    1. <script type="text/javascript">
    2.       var i = 0;
    3.       function creatediv()    
    4.      {
    5.             i++;
    6.             var newelement = document.createElement('div');
    7.             newelement.setAttribute('id', i);
    8.             newelement.innerHTML = 'This is newly created div.';
    9.             var parentelement = document.getElementById('presentdiv')
    10.             parentelement.appendChild(newelement);
    11.             //var firstchild = parentelement.firstChild;
    12.             //parentelement.insertBefore(newelement, firstchild);
    13.              
    14.      }
    15. </script>
    16. <html>
    17. <body>
    18.              <div id="presentdiv">This div is present here from the moment the page is opened.<input type="button" value="Click to create new div" onclick="javascript:creatediv();"></div>
    19. </body>
    20. </html>
Explanation:
First, we see the div 'presentdiv'. It has two nodes, first is the text node and another is input 'button'. New div is created on clicking button. How?
Look at the javascript function creatediv().

          6: A new div is created using createElement(). It takes the HTML tagname of element to be created as argument.

          7: setAttribtue() sets the attribute of the element using it. Like we have set 'id' as i, which is incrementing on every click.

          8: innerHTML is used if you want to add text to the element. Mostly used with div.

          9: We saved parentelement i.e., 'presentdiv' for further use instead of calling again and again.

          10: appendChild() is called to append  the element we just created, div(i). It appends at the end of the 'parentelement'.

          11: This line is used if we want to add new element at the beginning of parent element. 'firstChild' returns the first child of the 'parentelement'.

          12:  insertBefore() is used if new element is to be inserted before the some element we know. Here we insert 'newelement' before 'firstchild'.

Note: 
    Uncomment the line 11 and 12 if you want to insert 'newelement' before 'firstchild'.
    Also see lastChild and returning values of firstChild and lastChild.

Friday, October 21, 2011

Fetching from database using PHP

If you have database, then of course you will need to fetch data out of it. Four methods are described below to fetch from database and whats the difference between them.

Required: PHP, MySQL.

Using:

table1
name(varchar)

$query = "SELECT name FROM table1";
$rows = mysql_query($query);
$row = mysql_fetch_array($rows, $result_type); 
$row = mysql_fetch_assoc($rows);
$row = mysql_fetch_row($rows);
$row = mysql_fetch_object($rows, 'class', $params);

Note: All parameters are not defined here but are explained below.

Explanation:
Methods to fetch are described below:
  1. mysql_fetch_array($rows, $result_type): First argument, $rows is same as we have described earlier. Second argument is the result type which has three values MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH, which is default and this argument is optional.
    • MYSQL_ASSOC is used when we want to use associative key or table name for fetching. So, if we want to echo result it would be like
      echo $row['name'];
    • MYSQL_NUM is used if we are going to use numbers as associative keys also called index. It would go like
      echo $row[0].
    • MYSQL_BOTH is used if you don't know what you are going to use. With this way you can use both key and index.
  2. This is just the same as mysql_fetch_array() with result type argument as MYSQL_ASSOC. Syntax will be
    $row['name'];
  3. It is identical to mysql_fetch_array() with result type as MYSQL_NUM. Syntax will be
    echo $row[0];
  4. mysql_fetch_object($rows, 'class', $params): This is same as mysql_fetch_assoc() but instead of array this returns object of class 'class'. That is it can be accessed by only with column name in table. Syntax would be:
    echo class->name;
    The last argument, $params, is used when parameters are needed to be passed in constructor of 'class', it has to be array. Also $params is optional.
Note: All the fetch function are almost equivalent in terms of performance.
         Also see PHP manual on these function.

Wednesday, October 12, 2011

Creating a menu

Well there are two ways to create menu that I can think of. One is the Google's way, you click on it to get the menu items. Other is which we see on other sites when you hover on menu and it shows you the menu items.
But we will go the Google's way.

Required: Javascript, HTML

Using:
    1. <html>
    2. <script type="text/javascript">
    3. var toggle = 1; 
    4. function showmenuitems()
    5. {
    6.    if(toggle == 1)
    7.    {
    8.       document.getElementById('menuitems').style.visibility = 'visible';
    9.       toggle = 0;
    10.    }
    11.    else
    12.    {
    13.       hidemenuitems();
    14.       toggle = 1;
    15.    }
    16. }
    17. function hidemenuitems()
    18. {
    19.       document.getElementById('menuitems').style.visibility = 'hidden';
    20. }
    21. </script>
    22. <body>
    23. <p id="menu" onclick="showmenuitems()">Menu</p>
    24. <dl onblur="hidemenuitems()" id="menuitems" style="visibility:hidden; z-index:1">
    25. <dt>Item1</dt>
    26. <dt>Item2</dt>
    27. </dl>
    28. </body>
    29. </html>
Explanation:
If you will read the code you will find that all is done is using the visibility property of the dl. Here toggle variable helps us to determine the current state. A lot can be done with this code. For ex: if you click on the document except the paragraph menu items should hide, adding href to items etc etc.

Note: It is just basic way to implement the menu. Use your imagination to create something new.

Saturday, October 8, 2011

Comparing timestamp in MySQL

Required: MySQL

Using:
table1
         id (int)
         jointime(timestamp)

SQL query
  1. SELECT id FROM table1 WHERE jointime > '2011-10-08 00:00:00';
Explantion:
  1. This query selects id from table where jointime is greater than 2011-10-08.
Note:
  • Timestamp is a standard data type in MySQL and it should have both date and time.
  • For current time use NOW()
  • If you are using only date then use conversion from date to timestamp using TIMESTAMP()
  • With PHP
    • First get the time if current time use time(), it will give time in Unix Epoch.
    • Convert above time to timestamp using date() and then use in query.
    • If using some other time use mktime().
  • Remember the quotes they are important.
Also see MySQL timestamp datatype and PHP date time functions, also other functions.

Friday, October 7, 2011

Cool front page

There is a site on internet  We Are Empire. This site has pretty cool front page. Page is pretty descriptive too plus it don't irritate the user by reloading for new content. Some other site like this which I personally liked is Nike's nike better world site. It takes a little while to load but every information is on just single page and designed in awesome way using HTML5, z-index and many more things. We will come to it some other time.

But we will talk about the former one here. After running a console over the site, I understood what they had done. Well its nothing but Javascript and applaud to the maker, it is used very well for designing. It do not have flash.
  1. What they had done is when you click on the front logo which is image it shows you next div which is hidden behind it and hide the top div. 
  2. Now you see 4 bubbles. Thats interesting now margin of the image in background of the bubble changes when you hover it while hiding the overflow. This is a good thing, must have taken long time to do that.
  3. Open at the bottom is the coolest thing. Click on it and another page comes with no page loading. Again is the game of margin. Margin-top is changed using Javascript to animate.
  4. There are smaller effects also like close appearing and hiding, get in touch etc.
So, this is how this front page is working. Try making yours with such innovation.

Here is a example of that a very short one.

  1. <script type="text/javascript">
  2. function anim(mydiv)
  3. {
  4. var i = 0;
  5. while(i < 10)
  6. {
  7.         mydiv.style.marginTop = 10*i + 'px';
  8.         i++;
  9. }
  10. }
  11. </script>
  12. <div id="mydiv" onclick="javascript:anim(this)">
  13. test
  14. </div>

Protection from sql injection in PHP

There are many points which are needed to stop sql injection in PHP. One of them is discussed below.
We will focus on escaping the characters which allow sql injection. Let say we have a table:

Required: MySQL, PHP

Using:
table1:
         id (int)
         name (char)

Now if we use a query,

"SELECT id FROM table1 WHERE name = ".$name;

Here $name is a php vairable. Now lets try to hack this query. I will use one example here for that.
If we pass a value ALL (SELECT name FROM table1) into $name and it will reply to us with all the ids in table1. So in order to prevent such disaster we are going to use some methods of PHP itself.

First, is the mysql_real_escape_string() and the second one is addslashes().
While running query use the above functions like  addslashes(mysql_real_escape_string($name)).

Explanation:

mysql_real_escape_string() - what it does is escape the special characters in string. like hexadecimal.
addslashes() - this introduces slashed before the quotes.

Note:

  1. First use mysql_real_escape_string() then addslashes over it if you are entering value in database.
  2. To invert the procedure which will be needed when fetching values use stripslashes() twice over the value and it will give you the original value.

Thursday, October 6, 2011

Refreshing a particular div

Required: jquery-latest.js

Using:



Explanation:
              9. # is selector for id which is newcontent, a div here. Load method loads the content of file2.php in newcontent div.

file2.php
Note: Try not to write any HTML just process your data using php.

Text suggestion while writing in textbox using Javascript

Requirements: None, just javascript but good knowledge of that.

Using:
file.html
  1. <html>
  2. <body>
  3.       <input type="text" id="notrequired" onKeyUp="hint(this)" />
  4.        <div id="hintwords"></div>
  5. </body>
  6. <script type="text/javascript">
  7. function hint(me)
  8. {
  9. var arr = new Array('test','it','will','work');
  10. var iter = 0;
  11. var mat = new Array();
  12. var len = me.value.length;
  13. if(len>0)
  14. {
  15. for(iter=0 ; iter < arr.length; iter++)
  16. {
  17. var val = me.value;
  18. //alert(val);
  19. var patt = new RegExp( val ,'gi');
  20. var result = patt.exec(arr[iter]);
  21. if(result == val)
  22. {
  23. //alert(arr[iter]);
  24. mat.push(arr[iter]);
  25. }
  26. }
  27. //alert(mat[0]);
  28. var str = '';
  29. for(iter = 0; iter < mat.length ; iter++)
  30. {
  31. if(str == '')
  32. {
  33. str = str + mat[iter]
  34. }
  35. else
  36. {
  37. str = str + ',' + mat[iter]
  38. }
  39. }
  40. document.getElementById('hintwords').innerHTML = str;
  41. }
  42. else
  43. {
  44. document.getElementById('hintwords').innerHTML = '';
  45. }
  46. }
  47. </script>
  48. </html>
Explanation:
           I will be explaining just the lines that are important and needed to be explain.
     9.   array is created of the words that are needed to be hinted.
    13.  checking if the length of value of text in textbox is greater than 0.
    15.  looping on the length of the array of words.
    20.  making a regular expression using of the value of textbox. Here the regex generated will be the same as the value of textbox.
     21. checking for the match using exec() of regex.
     26. if there is match then the word that is from the array of word is pushed into new array mat.
     35. if the str has no value then this line is exceuted and string is concatenated to str.
     39. else this line concatenated to str.
     42. is just writing the str in the div hintwords.
     46. if the textbox has no value or empty then no hint is shown

                                                                                        Jquery post method for JSON in php files

                                                                                        Required: jquery.js(I use jquery-1.6.js. Download latest!)

                                                                                        Using: In file1.php


                                                                                          1. $(document).ready(function(){
                                                                                          2.           $.post( 'filename', {data : data}, function(data , status){ 
                                                                                          3.                      if(status == 'success')
                                                                                          4.                     { alert(data.name); //your code } 
                                                                                          5.           }, "json" );
                                                                                          6. });


                                                                                        In file2.php

                                                                                          1. if(isset($_POST['data'])){
                                                                                          2.         echo json_encode(array('name'=>$_POST['data']));
                                                                                          3. }
                                                                                        Explanation:
                                                                                         file1.php

                                                                                          1. checks if the current document is ready.
                                                                                          2. is the jquery method "post" is given arguments, first is the "filename" is the file name which you want to handle the post variables. Second is associative array sort of thing in which first "data" is name of the post variable and second "data" is the value of the variable. Third argument is the callback function, this executes when the post is complete. This function is provided two arguments, first is "data" which is the response from the file which is handling post. We will explain it after sometime. And the second is "status" it is optional in all of this without this code will still work. It actually holds the status of response.
                                                                                          3. checks if status is success
                                                                                          4. if status is success we use alert to check for the JSON value which is data.name and will alert "data" because we sent it back from file2.php.
                                                                                          5. "json" is the last argument of the post method which tells the that this method is expecting JSON as response.
                                                                                        Note: post variable name can be in quotes 'data'.
                                                                                                 argument status can be omit.
                                                                                                 "json" is required as argument if you want response to be JSON.

                                                                                        file2.php
                                                                                          1. checks if $_POST['data'] is set. The data index is the same variable name we have sent from file1.php.
                                                                                          2. first we create an associative array with key as "name" and value as $_POST['data']. Then we encode it in JSON using json_encode and echo it, which is accepted by first file in callback function as data and checked using alert in file1.php as data.name which is the key in associative array.
                                                                                        Note:
                                                                                                this file should not have any of HTML code.
                                                                                                this file should not echo anything other than JSON.
                                                                                                you can use include() but above two points should always hold.


                                                                                        Hope this will help you in case you find trouble.