Skip to main content

Posts

Showing posts from 2012

Javascript: Reserved words

Javascript: Reserved words In JavaScript, reserved words are a combination of keywords used for JavaScript and words that are reserved for use in future versions of JavaScript. You must be extremely careful not to use reserved words for the names of variables, functions, methods, or objects. The list of reserved words generally includes 59 different words, we also added a couple that the programmers are not sure about yet. The typical list of 59 reserved words is as follows.

Javascript - Page printing

Javascript - Page printing Many times you want to print the page or print any forms or informations. So this function is very helpful for all the web- programmers. The JavaScript print function window.print() will print the current web page when executed. You can call this function directly using onclick event as follows:

Javascript: Page redirection

Javascript: Page redirection Page redirection is very usefull technique for website development. If a user opens an x page then by using redirection method you can tell to open y page. But still users think they are viewing x page. This is very helpfull in the case when you move your domain name. And when some one enters the same url you can redirect to some other site without actually disturbing the visitors or any interuptions.

HTML 5: Different input types - input type url

Similarly as the input type email earlier, an another input type is url. It also validate if the user has inputed url or not. If not it shows message as before.

HTML 5: Different input types - input type email

HTML 5 have added many input types. This is one of the feature which really has made HTML 5 awesome and interesting to use. Those some input types are as below: - email - url - number - tel - date

HTML 5 Form Validations

HTML 5 has introduced Javascript plug-ins to achieve something similar effect. But these code will only work in Safari 5, Chrome 6, Opera 9, Firefox 4 Beta and the iPhone/iPad. Also each browser has a slightly different default behaviour. The "required " attribute The simplest change you can make to your forms is to mark a text input field as 'required':

Different versions of HTML

HTML is an evolving language, and each new version is given a number. The first definitive version was HTML 2.0 -- this had most of the elements we know and love, but was missing some of the Netscape/Microsoft extensions, and did not support tables, or ALIGN attributes. HTML 3 (late 1995) was an ambitious effort on the part of Dave Raggett to upgrade the features and utility of HTML. However, it was never completed or implemented, although many features were integrated in the next "official" version of HTML, known as HTML 3.2.

Javascript for Loop

The for loop is the most compact form of looping and includes the following three important parts: The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.  The test statement which will test if the given condition is true or not. If condition is true then code given inside the loop will be executed otherwise loop will come out.  The iteration statement where you can increase or decrease your counter.

Javascript While Loop

While programming, there might be situation that you need to execute a block of code for a given number of times, in these situation while loop can be used. The while loop executes code while a condition is true. Syntax: while (expression){    Statement(s) to be executed if expression is true }   Example: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Siple Javascript conditions</title> </head> <body> <button onclick="myLoop()">Click Me</button> <script> function myLoop() { var count=0; while(count <=10) { document.write("Number: "+count+"<br/>");    count ++; } } </script> </body> </html>

Download XAMPP

XAMPP is a very easy to install Apache Distribution for Linux, Solaris, Windows and Mac OS X. The package includes the Apache web server, MySQL, PHP, Perl, a FTP server and phpMyAdmin. Download XAMPP from below locations: Download From Sourceforge Download From CNET Download From DownloadXamp

Encapsulation in PHP

Encapsulation is wrapping some data in an object. It is about controlling the visibility of things and define something like the order of layers of our application. Encapsulation in PHP OOP is about control and limit which parts of our application can access some class methods and properties using three keywords called in OOP world Access Control Modifiers , and these keywords are : public , private , protected   and this keyword comes in the beginning of declaring method or property just like below : class Member {   public $id;   protected $username;   private $password; } Public keyword modifier is used to define a variable or function as being visible to everyone, everywhere.  When this modifier is used the variable or function following is visible to the users using your class as well as all the inner workings of your class.  This modifier is the only modifier that allows interaction outside of the class. Private keyword modifier is use...

Sending mail from localhost

Okay now you want to test the mail function but wait you don't have any domain name or online site to do this. So what can you do in this situation. Simply send email from your localhost. Ya!! That's correct sending mail from your local computer and local files which are not hosted yet. And yes you can do this. For this follow the steps below: 1) First open php.ini file. 2) Search for the mail function. When you find something like below. Okay you have found it. 3) Now configure that mail function as below: [mail function] ; For Win32 only. ; http://php.net/smtp SMTP = smtp.wlink.com.np ; http://php.net/smtp-port smtp_port = 25 4) Okay this is good now next step. Search for the below line and configure the email address that you want to sent other emails. ; For Win32 only. ; http://php.net/sendmail-from ;sendmail_from = you@yourdomain 5) Remove semicolon(;) and write your email address as below: ; For Win32 only. ; http://php.net/sendmail-from sendmail_from = hello@gmail.com 6...

CSS: Different versions with variations

CSS 1: The first CSS specification to become an official W3C Recommendation is CSS level 1, published in December 1996. Among its capabilities are support for     Font properties such as typeface and emphasis     Color of text, backgrounds, and other elements     Text attributes such as spacing between words, letters, and lines of text     Alignment of text, images, tables and other elements     Margin, border, padding, and positioning for most elements     Unique identification and generic classification of groups of attributes The W3C no longer maintains the CSS 1 Recommendation.

JavaScript Switch Statement

Use the switch statement to select one of many blocks of code to be executed. Syntax switch(n) { case 1:   execute code block 1   break; case 2:   execute code block 2   break; default:   code to be executed if n is different from case 1 and 2 } Example: var day=new Date().getDay(); switch (day) { case 0:   x="Today it's Sunday";   break; case 1:   x="Today it's Monday";   break; case 2:   x="Today it's Tuesday";   break; case 3:   x="Today it's Wednesday";   break; case 4:   x="Today it's Thursday";   break; case 5:   x="Today it's Friday";   break; case 6:   x="Today it's Saturday";   break; }

Javascript conditional statement

When you need to make program to make decisions, conditional statements are used. In javascript we have following conditional statements:  if statement - use this statement to execute some code only if a specified condition is true if...else statement - use this statement to execute some code if the condition is true and another code if the condition is false  if...else if....else statement (nesting of if else)- use this statement to select one of many blocks of code to be executed switch statement - use this statement to select one of many blocks of code to be executed If Statement: Executes the code if a specific code is true Syntax: if(condition) { code } Example: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=u...

Comparison and Logical Operators

Comparison and Logical operators are used to test for true or false. Comparison Operators  Comparison operators are used in logical statements to determine equality or difference between variables or values. Given that x=5, the table below explains the comparison operators: Operator Description Comparing Returns == is equal to x==8 false x==5 true === is exactly equal to (value and type) x==="5" false x===5 true != is not equal x!=8 true !== is not equal (neither value nor type) x!=="5" true x!==5 false > is greater than x>8 false < is less than x<8 true >= is greater than or equal to x>=8 false <= is less than or equal to x<=8 true Logical Operators Logical operators are used to determine the logic between variables or values. Given that x=6 and y=3 , the table below explains the logical operators: Operator Description Example ...

Doctype Defination

A Document Type Declaration, or DOCTYPE, is an instruction that associates a particular SGML or XML document (for example, a webpage) with a Document Type Definition (DTD). Syntax The general syntax for a document type declaration is: <!DOCTYPE root-element PUBLIC "FPI" ["URI"] [ <!-- internal subset declarations --> ]>

Accessible Forms

Forms aren't the easiest of things to use for people with disabilities. Navigating around a page with written content is one thing, hopping between form fields and inputting information is another. Because of this, it is a good idea to add a number of elements to the form. Labels Each form field should have its own label. The label tag sorts this out, with a for attribute that associates it to a form element:

Advanced Tables

Okay till now, you must be confident with creating tables and its tags. You have already done or used tags like table, tr, td, th and even rowspan and colspan. So now I am moving on to the advance tutorial of the table tags. Those are as below: colgroup and col summary and caption headers, footers and scrolling table

Quotations

Quotations blockquote, q and cite are used for quotations. blockquote is block-line and used for large citations, whereas q is in-line and used for smaller phrases. cite is also in-line and preferable to q for its semantic nature and possible future deprecation of q. Again, the title attribute can be used to show where the citation has come from.

Abbreviations and acronyms

abbr and acronym are used for abbreviations and acronyms respectively. An abbreviation is a shortened form of a phrase. Very general. An acronym however is an abbreviation made up of the initial letters (or parts of words) of the phrase it is representing. So CSS is a valid acronym, whereas HTML and XHTML are not (if 'Hypertext markup language' was an acronym, it would be 'HML'. Similarly, XHTML would be EHML).

Definition Lists

Definition Lists The dl element gets the ball rolling, similar to the ul and ol elements, establishing the list. Rather than there being an li element though, definition lists have a dt element, which is the definition term, followed by a dd element which is a definition description associated to the dt element. There doesn't have to be one dt followed by one dd, there can be any number of either. For example, if there are a number of words that have the same meaning, there might be a number of dt's followed by one dd. If you have one word that means various different things, there might be one dt followed by several dd's.

Javascript events

Javascript events Javascript is all about cool stuffs displayed in the website. So here we will learn how these cool stuffs happens in the website. This all are the ability of Javascript which increase the user interaction and flash like features. The building blocks of an interactive web page is the JavaScript event system. An event in JavaScript is something that happens with or on the webpage. A few example of events:     A mouse click     The webpage loading     Mousing over a hot spot on the webpage, also known as hovering     Selecting an input box in an HTML form     A keystroke For example: <html> <head> <script type="text/javascript"> <!-- function popup() {     alert("Wow!! I feel good.") } //--> </script> </head> <body> <input type="button" value="Click Me!" onclick="popup()"><br /> <a href="#" onmouseover="" onMouseout...

Javascript Array

Javascript Array An array is a variable that can store many variables within it. Many programmers have seen arrays in other languages, and they aren't that different in JavaScript. Creating a JavaScript Array Creating an array is slightly different from creating a normal variable. Because JavaScript has variables and properties associated with arrays, you have to use a special function to create a new array. This example shows how you would create a simple array, store values to it, and access these values. JavaScript Code: <script type="text/javascript"> <!-- var myArray = new Array(); myArray[0] = "Football"; myArray[1] = "Baseball"; myArray[2] = "Cricket"; document.write(myArray[0] + myArray[1] + myArray[2]); //--> </script> Output: FootballBaseballCricket JavaScript Array Sorting Imagine that you wanted to sort an array alphabetically before you wrote the array to the browser. Well, this code has already been written...

Constructors and Destructors

Constructor PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used. Syntax: void __construct ([ mixed $args [, $... ]] ) For example: <?php class constExample{     function __construct()     {         echo "This will execute without calling a method";     }     } $obj = new constExample(); ?> Destructors PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence. Syntax: void __destruct ( void ) For example: <?php class MyDestructableClass {    function __construct() {      ...

Class and object

Creating a Class: To create a class use the class keyword and a name. Class names can be any combination of numbers and letters, although they must not begin with a number. The code associated with a class must be enclosed within braces. Class Defination: <?php class ClassName {   // class body } ?> For example: <?php class Books{ public $name; public $author; public function showBook(){ $name="Munna Madan"; echo $name; } } ?> Setting Properties and Methods In the class body are defined its properties and methods.         - Properties are variables defined inside the class.         - Methods are functions created within the class, with the word "function". The name of the variable (property) and the "function" word must be preceded by a specific attribute that determines the level of access that is allowed for the property or the method to be accessed outside its class. This can be: public, protec...

Object Oriented Programming

PHP is an object- oriented programming language. What is object-oriented programming (OOP)? Object-oriented programming(OOP) is a programming language using objects usually instances of a class, consisting of data fields and methods together with their interactions to design applications and computer programs. Main features of OOP are as below:  Class and object:     A class is a group of objects and an object is an instance of a class. It contains the code for properties and methods. Encapsulation:     Encapsulation is the ability of an object to protect the data (properties) of a class from outside influences. You can use a class (its properties) through an object instance, without having access to its code. Inheritance:     Inheritance is the ability of a class to copy or inherit the properties and methods of a parent class. Polymorphism:     Polymorphism is a class ability to do more different things, or use one clas...

Javascript popup window

Javascript popup window is the small window which is created by javascript. The syntax for javascript popup window is given below: window.open(url, name, [windowFeatures]) where url: The url of the page to open in the new window. name: A name is the name of the window. windowFeatures: They are the parameters which determines the various features of window to be included in the popup window like status bar, address bar,width,height, etc. The table shows the features and the string tokens you use: status     The status bar at the bottom of the window. toolbar     The standard browser toolbar, with buttons such as Back and Forward. location     The Location entry field where you enter the URL. menubar     The menu bar of the window directories     The standard browser directory buttons, such as What’s New and What’s Cool resizable     Allow/Disallow the user to resize the window....

Javascript: alert box, prompt box and confirm box

Alert box: It displays an alert dialog with a text message and OK button Example: Code: <html> <head> <script type=”text/javascript”> function showAlert() {     alert(“Hey!! This is an alert box”); } </script> </head> <body> <input type=”button” onClick=”showAlert()” value=”Show” /> </body> </html> In above example, only the text Hey!! This is an alert box appears. Prompt Box: Prompt is used to allow a user to enter something, and do something with that value. Code: <html> <head> <script type=”text/javascript”> function showPrompt() {     var name=prompt(“Please enter your name”, “Awaken Nepal”);     if(name!=null && name!=”")     {     document.write(“Hello”+name+”! How are you?”);     } } </script> </head> <body> <input type=”button” onClick=”showPrompt()...

To show/hide any content using javascript

Code: <script language=”javascript”> function showContent() { var ele = document.getElementById(“toggleText”); var text = document.getElementById(“displayText”); if(ele.style.display == “block”) { ele.style.display = “none”; text.innerHTML = “show”; } else { ele.style.display = “block”; text.innerHTML = “hide”; } } </script> <a id=”displayText” href=”javascript:showContent();”>show</a> <== click Here <div id=”toggleText” style=”display: none”><h1>This is hidden content</h1></div> Output: Before link is clicked After link is clicked  

HTML Layouts – Using Tables

Website Layouts Website Layout is very important to make your website look good. So you need to design your website properly. There is two ways of designing layout.  Using Table Using CSS(Without using table) Here, we will discuss using tables.

Nesting of Table

To use table inside of another table is called nesting of tables. As according to the need, we might need to show different information in an appropriate ways, so we need table inside another table.

HTML Frames

With frames, several Web pages can be displayed in the same browser window. Note: Do not expect frames to be supported in future versions of HTML. Frames allow for multiple .html documents to be displayed inside of one browser window at a time. This means that one page has no content on it, but rather tells the browser which web pages you would like to open. With the addition of CSS and PHP, frames have become outdated. The disadvantages of using frames are:     Frames are not expected to be supported in future versions of HTML     Frames are difficult to use. (Printing the entire page is difficult).     The web developer must keep track of more HTML documents The HTML frameset Element The frameset element holds one or more frame elements. Each frame element can hold a separate document. The frameset element states HOW MANY columns or rows there will be in the frameset, and HOW MUCH percentage/pixels of space will occupy e...

HTML Forms

HTML forms are used to pass data to a server. A form can contain input elements like text fields, checkboxes, radio-buttons, submit buttons and more. A form can also contain select lists, textarea, fieldset, legend, and label elements. The <form> tag is used to create an HTML form:

MySQL: SQL

SQL is a standard language for accessing and manipulating databases. To connect any and every database and to execute, insert, update or delete any records, we need SQL.. Brief description about SQL:     SQL stands for Structured Query Language     SQL lets you access and manipulate databases     SQL is an ANSI (American National Standards Institute) standard What Can SQL do?     SQL can execute queries against a database     SQL can retrieve data from a database     SQL can insert records in a database     SQL can update records in a database     SQL can delete records from a database     SQL can create new databases     SQL can create new tables in a database     SQL can create stored procedures in a database     SQL can create views in a database     SQL can set permissi...

MySQL Connection

Connection with MySQL Database Before accessing database, you must create a connection to the database Syntax: mysql_connect(servername,username,password); where, servername specifies the server to connect to. Default value is “localhost” username specifies the username to log in with. Default value is the name of the user that owns the server process. To connect offline we use username “root”. password specifies the password to log in with. Default is “” Code : Creating connection to the database and selecting the required database <?php $con = mysql_connect(“localhost”,”root”,”"); if (!$con) { die(‘Could not connect: ‘ . mysql_error()); } else{ mysql_select_db(“test”, $con) }; ?> Here, we have store connection in a variable called $con and trap error using die function. Closing connection The connection will be closed automatically when the script ends. To close the connection before, use the mysql_close() function: <?php $con = mysql_conne...

MySQL: Introduction

MySOL is a database. With PHP, default database is MySQL. Database is needed to create any dynamic website or web application. Records or information for any website is kept in database in the forms of tables. Table is the collection of related data entries and it consist of columns and rows. A row of information is called tuple. What is Query? Query is a question or a request. With the help of query you can show, add,edit and delete any record. How to create database? Its very simple, just open your database, create database as below: 1)Open link http://localhost/phpmyadmin. 2)Click on the database tab. 3)Give name of database and create like below.   now  I will inside the database called test as below: How to create tables? 1)Once you have created database, click on the database. For example, I have created a database called test. So  2) Create table on the database test. 3) Give table name and number of fields needed and click on c...

PHP Error Handling

All the possible errors should be managed in such a way, it should be debugged properly. So in this case default error handling is used which is very simple. An error message with filename, line number and a message describing the error is sent to the browser. Error handling is an important part while creating any web applications or scripts or pages. If you want your viewers to not display any errors on your web page then you following code on the top of your page:    error_reporting(0); or if you only want to see Warning Messages and not Notice Messages: ini_set('display_errors',1); error_reporting(E_ALL); Error Handling with die() function Lets try using a simple example below: Code: <?php if(isset($_POST['submit'])){ $filename=$_FILES['image']['name']; $tmp_name=$_FILES['image']['tmp_name']; if(!move_uploaded_file($tmp_name,"img".$filename)){ die("Error in uploading"); } else { print("Up...

Sending Emails

PHP makes use of mail() function to send an email. This function requires three mandatory arguments that specify the recipient’s email address, the subject of the the message and the actual message additionally there are other two optional parameters. mail( to, subject, message, headers, parameters ); Here is the description for each parameters. Parameter Description to Required. Specifies the receiver / receivers of the email subject Required. Specifies the subject of the email. This parameter cannot contain any newline characters message Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters headers Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n) parameters Optional. Specifies an additional parameter to the sendmail program As soon as the mail function is called PHP will attempt to send the email then...

PHP Sessions

A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit. A session ends when the user loses the browser or after leaving the site, the server will terminate the session after a predetermined period of time, commonly 30 minutes duration. Starting a PHP Session: A PHP session is easily started by making a call to the session_start() function.This function first checks if a session is already started and if none is started then it starts one. It is recommended to put the call to session_start() at the beginning of the page. Session variables are stored in associative array called $_SESSION[]. These variables can be accessed during lifetime of a...

PHP Cookies

A cookie is often used to identify a user.A cookie is a tiny little file on your client’s hard drive which contains data you have asked to be stored. Some clients specifically configure their browser to reject cookies, believing for one reason or another that they are malicious, and there is nothing you can do about this – that person’s browser will not be able to store your data. When creating cookies, you specify how long you want it to be valid for, and, once done, the cookie remains in place until that date, when it “expires”. Cookies are automatically sent to the web server (and received/parsed by PHP) each time a user visits you. That means that once we place our cookie, our visitors’ browsers will automatically send the contents of that cookie across to us each time they view our messageboard index, and PHP will read the value into the $_COOKIE superglobal array. As cookies are sent each time, it is incredibly important not to store too much information there – they can real...

Some useful functions for manipulating array

Function Explanation Example sizeof($arr) This function returns the number of elements in an array.Use this function to find out how many elements an array contains; this information is most commonly used to initialize a loop counter when processing the array. Code: $data = array("red", "green", "blue");echo "Array has " . sizeof($data) . " elements"; ?>Output: Array has 3 elements array_values($arr) This function accepts a PHP array and returns a new array containing only its values (not its keys). Its counterpart is the array_keys() function.Use this function to retrieve all the values from an associative array. Code: $data = array("hero" => "Holmes", "villain" => "Moriarty"); print_r(array_values($data)); ?>Output: Array ( [0] => Holmes [1] => Moriarty ) array_keys($arr) This function accepts a PHP array and returns a new array containing only its key...

Differences between echo, print and print_r in PHP

echo : Outputs one or more strings. And echo is not a function, but a language construct. echo has a void return type.echo is not actually a function (it is a language construct), so you are not required to use parentheses with it. echo (unlike some other language constructs) does not behave like a function, so it cannot always be used in the context of a function. Additionally, if you want to pass more than one parameter to echo, the parameters must not be enclosed within parentheses. For example: <?php   echo “Hello World”; ?> echo also has a shortcut syntax, where you can immediately follow the opening tag with an equals sign. This short syntax only works with the short_open_tag configuration setting enabled. For example: My name is <?=$name; ?>. Note: However, short tags are discouraged to use in modern versions on PHP.. print: print is not actually a real function (it is a language construct) so you are not required to use parentheses with its argument list. ...

PHP File Upload

Create an Upload-File Form To allow users to upload files from a form can be very useful. Look at the following HTML form for uploading files: <html> <body> <form action=”upload_file.php” method=”post” enctype=”multipart/form-data”> <label for=”file”>Filename:</label> <input type=”file” name=”file” id=”file” /> <br /> <input type=”submit” name=”submit” value=”Submit” /> </form> </body> </html> Notice the following about the HTML form above: The enctype attribute of the <form> tag specifies which content-type to use when submitting the form. “multipart/form-data” is used when a form requires binary data, like the contents of a file, to be uploaded The type=”file” attribute of the <input> tag specifies that the input should be processed as a file. For example, when viewed in a browser, there will be a browse-button next to the input field Note: Allowing users to upload files is a big security risk. Only permit...

PHP File

Opening a File The fopen() function is used to open files in PHP. The first parameter of this function contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened: <html> <body> <?php $file=fopen("welcome.txt","r"); ?> </body> </html> Note: If the fopen() function is unable to open the specified file, it returns 0 (false). Example The following example generates a message if the fopen() function is unable to open the specified file: <html> <body> <?php $file=fopen("welcome.txt","r") or exit("Unable to open file!"); ?> </body> </html> Modes Description r Read only. Starts at the beginning of the file r+ Read/Write. Starts at the beginning of the file w Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist w+ Read/Write. Opens and clears the content...

PHP Include

Server Side Includes (SSI) You can insert the content of one PHP file into another PHP file before the server executes it, with the include() or require() function. The two functions are identical in every way, except how they handle errors:     include() generates a warning, but the script will continue execution     require() generates a fatal error, and the script will stop These two functions are used to create functions, headers, footers, or elements that will be reused on multiple pages. Server side includes saves a lot of work. This means that you can create a standard header, footer, or menu file for all your web pages. When the header needs to be updated, you can only update the include file, or when you add a new page to your site, you can simply change the menu file (instead of updating the links on all your web pages). PHP include() Function The include() function takes all the content in a specified file and includes it in the...