Pages

Sunday, 8 July 2012

jquery


jQuery is a JavaScript Library whivh greatly simplifies JavaScript programmingand is easy to learn.Everyone shall mess up saying we already have javascript than what is use of jQuery than the answer is (Write less, do more)this is the moto of jQuery.jQuery simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.
jQuery is a JavaScript toolkit designed to simplify various tasks by writing less code. Here is the list of important core features supported by jQuery:

DOM manipulation: The jQuery made it easy to select DOM elements, traverse them and modifying their content by using cross-browser open source selector engine calledSizzle.

Event handling: The jQuery offers an elegant way to capture a wide variety of events, such as a user clicking on a link, without the need to clutter the HTML code itself with event handlers.

AJAX Support: The jQuery helps you a lot to develop a responsive and feature-rich site using AJAX technology.

Animations: The jQuery comes with plenty of built-in animation effects which you can use in your websites.

Lightweight: The jQuery is very lightweight library - about 19KB in size ( Minified and gzipped ).

Cross Browser Support: The jQuery has cross-browser support, and works well in IE 6.0+, FF 2.0+, Safari 3.0+, Chrome and Opera 9.0+

Latest Technology: The jQuery supports CSS3 selectors and basic XPath syntax.

For downloading latest version of jquery click on the below link copy the content at save it as jquery-1.3.2.min.js file in a directory of your website, e.g. /jquery.


A simple program describing syntax of jquery is as below:-
<html>
<head>
<title>The jQuery Example</title>
   <script type="text/javascript" src="/jquery/jquery-1.7.2.min.js"> //including jquery file
</script> 
   <script type="text/javascript">
      // you can add our javascript code here 
   </script>   
</head>
<body>
........ // your content here
</body>
</html>

jquery functions and examples:-

1.$(this).hide():-
This function Demonstrates the jQuery hide() method, hiding the current HTML element.

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $(this).hide();
  });
});
</script>
</head>

<body>
<button>Click me</button>
</body>
</html>
Example Explanation:-
The output of above code is a simple button where Click me is 
written and when we click on that it disappers providing a 
dynamic sensation.similarly we can write p,.test,#test in place 
of this as we now this can only be applied to one elements 
Demonstrates the jQuery hide() method, hiding all <p> elements.

Friday, 6 July 2012

PHP and XML

Let us first of all know what is XML.We easily say XML is Extened Markup Language which somehow feels like HTML which is also a markup language but much different from XML.Let us  now fhift to XML.
XML is a markup language that looks a lot like HTML. An XML document is plain text and contains tags delimited by < and >.There are two big differences between XML and HTML:
1.XML doesn't define a specific set of tags you must use.
2.XML is extremely picky about document structure.



In XML all the tags are "invented" by the author of the XML document.This is because the XML language has no predefined tag but tags used in HTML are predefined. HTML documents can only use tags defined in the HTML standard (like <p>, <h1>, etc.).XML allows the author to define his/her own tags and his/her own document structure.
XML is Not a Replacement for HTML but is a complement to HTML.XML is very strict when it comes to document structure. HTML let us play fast and loose with some opening and closing tags. But this is not the case with XML.



XML is used in many aspects of web development, often to simplify data storage and sharing.
1.XML Separates Data from HTML
2.XML Simplifies Data Sharing
3.XML Simplifies Data Transport
4.XML Simplifies Platform Changes
5.XML Makes our Data More Available
6.XML is Used to Create New Internet Languages

 

Now we have studied uses of XML let us now talk about its syntax rules:-
XML Syntax Rules

1.All XML Elements Must Have a Closing Tag.
For example:- <Message>This is incorrect</message>

2.XML Tags are Case Sensitive.

For example:-
<Msg>This is incorrect</msg>
 <msg>This is correct</msg>


3.XML Elements Must be Properly Nested.
For example:-
<b><i>This text is bold and italic</b></i>
//this is correct statement in html but incorrect in xml
4.XML Documents Must Have a Root Element.
XML documents contains one element that is the parent of all other elements. This element is called the root element.
The suntax is:-
<root>
<child>
<subchild>.....</subchild>
</child>


</root>

 
Now we take a simple example of xml:-


<bookstore> //it is simple root element
<book category="CHILDREN">
<title>Harry Potter</title> //subchild

<author>J K. Rowling</author>  //subchild
<year>2005</year>
          //subchild
  <price>29.99</price>    
//subchild
</book>
<book category="WEB">
<title>Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>

Wednesday, 4 July 2012

PHP+AJAX

Let us first of all know what is AJAX.AJAX stands for Asynchronous JavaScript and XML.AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS and Java Script.AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes.So,the point is we do not need to reload the whole page but just a small area undation will solve the purpose for client as well as server.
AJAX is based on internet standards, and uses a combination of:
1.XMLHttpRequest object (to exchange data asynchronously with a server)
2.JavaScript/DOM (to display/interact with the information)
3.CSS (to style the data)
4.XML (often used as the format for transferring data)
There is one main role of AJAX as the applications are browser- and platform-independent.
Let us take a simple example:-

<html>
 <head>
 <script language="javascript">

function postRequest(strURL)
{
var xmlHttp;
 if (window.XMLHttpRequest)  //For Mozilla, Safari, ...
{
var xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject)  //For InternetXplorer
{
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open('POST', strURL, true);
xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4){
updatePageTime(xmlHttp.responseText);
}
}
xmlHttp.send(strURL);
}
function updatePageTime(str)
{
 document.getElementById("result").innerHTML =
"<font color='blue' size='6'>" + str + "</font>";;
}

function getCurrentServerTime(){
var rnd = Math.random();
var url="currentservertime.php?id="+rnd;
postRequest(url);
}

</script>

 </head>
 <body>
<div align="center">
<form><input type="button" value="Show current server time" onclick="getCurrentServerTime()"></div>
<div id="result" align="center"></div>
 </body>
</html>

In this program we will see a button in center of page displaying  (Show current server time) and when we click on this button we will see our system displays current date and time.Like below:-


Thursday Jul 05th, 2012, 15:56:59

Tuesday, 3 July 2012

PHP + DATABASE

PHP will work with virtually all database software, including Oracle and Sybase but most commonly used is freely available MySQL database.
For this we need to have mysql database.But don't worry we have a mysql database already in our XAMPP installed. We just need to open our XAMPP Control Panel and click on admin button placed along the side of stop button.This will open up your phpmyAdmin page on your WebBrowser.After this on window we will see option providing database creation.Set a Suitable name for your database and after this press the create button after that option of creating tables will appear .From now we need to give a name to our table,specify the number of columns in our table as well there datatypes and other attributes as required.This was all one need to know before beginning. 

Creating a Connection to a MySQL Database:-

The syntax for establishing a MySQL connection is a below. mysql_connect(servername,username,password);

Here mysql_connect is the inbuilt function and all other fields are the optional values for example 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 and password Specifies the password to log in with. Default is "".

Let us now take a simple example:-

Example

In the following example we store the connection in a variable ($con) for later use in the script. The "die" part will be executed if the connection fails:

<?php
$con = mysql_connect("localhost","bajaj","bajaj123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }


// some code
?> 

The output of above program is Could not connect only if no such username exists or the password is incorrect else a blank screen appears.

Now we study creating a database:-

<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
$sql = 'CREATE Database test_db';
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not create database: ' . mysql_error());
}
echo "Database test_db created successfully\n";
mysql_close($conn);
?>
If the output of above code is Database test_db created successfully
then it is sure that our database is created otherwise something is going
wrong and we need to check output error and solve it.
 
Selecting a Database:-
<?php
$dbhost = 'localhost';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass); //conn is the connection name
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db( 'test_db' ); //test_db is the database name
mysql_close($conn);
?> 

Creating tables:-
 
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
$sql = 'CREATE TABLE employee( '.
       'emp_id INT NOT NULL AUTO_INCREMENT, './/proving column names and its attributes
       'emp_name VARCHAR(20) NOT NULL, '.     //proving column names and its attributes

       'emp_address  VARCHAR(20) NOT NULL, '. //proving column names and its attributes

       'emp_salary   INT NOT NULL, '.         //proving column names and its attributes

       'join_date    timestamp(14) NOT NULL, './/proving column names and its attributes

       'primary key ( emp_id ))';

mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not create table: ' . mysql_error());
}
echo "Table employee created successfully\n";
mysql_close($conn);
?>

 

Monday, 25 June 2012

Sending Emails In PHP

Our first step in sending email is locating php.ini file in htdocs folder and then editing.
PHP must be configured correctly in the php.ini file with the details of how your system sends email. Open php.ini file available in /etc/ directory and find the section headed [mail function].We try and find the WORD SMTP and a description shall be made there in place of the description write your "ip" address
in place of  localhost.This will solve the purpose.(press Ctrl+F) and write SMTP and find next and so on.
Windows users should ensure that two directives are supplied. The first is called SMTP that defines your email server address. The second is called sendmail_from which defines your own email address.
SYNTAX:-
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.

Below is a simple program for sending email:-

<html>
<head>
<title>Sending email using PHP</title>
</head>
<body>
<?php
  $to = "abc@domainName.com";
$subject = "This is subject";
$message = "This is simple text message.";
  $header = "From:pqr@domainName.com \r\n";
$retval = mail ($to,$subject,$message,$header);
if( $retval == true )
{
echo "Message sent successfully...";
}
else
{
echo "Message could not be sent...";
}
?>
</body>
</html>

PHP (Destroying Session)

Destroying a PHP Session:
A PHP session can be destroyed  by session_destroy() function. This function does not need any argument and a single call can destroy all the session variables. If we have a single session we can solve purpose by using unset() function.
Let us see now how it works.
/*
below we see counter which is our previously created counter.
but if we don't know the name or we want to destroy multiple sessions we use destroy function
*/
<?php
unset($_SESSION['counter']);
?>
*******************************
<?php
session_destroy();
?>
*******************************
More On Sessions:-
We will now learn turning sessions automatically.we just need to edit one file for this purpose.

Turning on Auto Session:
In this case we have no need to call start_session() function to start a session when a user visits our site if you set session.auto_start variable to 1 in php.ini file and we can find this file in the htdocs folder.

Sessions without cookies:

There may be a case when a user does not allow to store cookies on the machine. So there is another method to send session ID to the browser.

Alternatively, you can use the constant SID which is defined if the session started. If the client did not send an appropriate session cookie, it has the form session_name=session_id. Otherwise, it expands to an empty string. Thus, one can embed it unconditionally into URLs.

The following example demonstrates how to register a variable, and how to link correctly to another page using SID.

PHP Sessions STARTING

Starting of PHP Sessions:-
Our first step is to initialise function  session_start(); This will check if any other session have been already been started or not.If it is not this function will start it .Session variables are stored in associative array called $_SESSION[]. These variables can be accessed during lifetime of a session.
Now Let us have a look over a simple program related to starting of seesion.


/*
 The code below starts a session then register a variable called counter that is incremented each time the page is visited during the session.We must make sure
the use of isset() function to check if session variable is already set or not.
*/

<?php
  session_start(); //initialising the function
if( isset( $_SESSION['counter'] ) )
{
$_SESSION['counter'] += 1;
}
else
{
$_SESSION['counter'] = 1;
}
$msg = "You have visited this page ". $_SESSION['counter'];
$msg .= "in this session.";
?>
<html>
<head>
<title>Setting up a PHP session</title>
</head>
<body>
<?php echo ( $msg ); ?>
</body>
</html>

We must take note tto save this file as .php extension not as a html file although we see some html tags in use here.