Wednesday 16 July 2014

Die() & Exit() Function's in PHP.

The Die() function in php is used for generally printing the message or we can say output.


For Example (i)-


<?php

$conn=mysql_connect("localhost","root","") or die("connection not found");

?>


Example (ii)-

<?php

           $x=5;
           $y=5.2;

if($x==$y)
{
           exit('both are equal');

}

else
{
           exit('both are not equal');
}

?>

The exit( ) function in php is alias of die( ) funciton. It is also used to printing the message.


For Example (i)-


<?php

$conn=mysql_connect("localhost","root","") or die("connection not found");

?>


Example (ii)-


<?php

$x=5;
$y=5.2;

if($x==$y)
{

exit('both are equal');

}

else
{

exit('both are not equal');
}

?>

Full list of Aliases function you will find on following URL:

http://php.net/manual/en/aliases.php


Posted By -Amit Tiwari

Sunday 13 July 2014

What is the difference between PhP4 & PhP5 ?

There are many differences between PHP4 and PHP5-

  1. PHP5 was powered by Zend Engine II,while PHP4 was powered by Zend Engine 1.0
  2. In PHP5 abstract classes are used but not used in PHP4.
  3. In PHP5 interfaces are used but not used in PHP4.
  4. In PHP5 visibility are used but not used in PHP4.
  5. In PHP5 magic methods (such as __call, __get, __set and __toString)are used but not uesd in PHP4.
  6. In PHP5 typehinting are used but not used in PHP4.
  7. In PHP5 incorporates static methods and properties.
  8. In PHP5 cloning are used but not used in PHP4.
  9. In PHP5 construtor are written as __construct keyword but in PHP4 are written as class name.
  10. In PHP5 special function intorduces called __autoload()
  11. In PHP5 there is new error level defined as ‘E_STRICT’
  12. In PHP5 there is new default extensions such as SimpleXML, DOM and XSL, PDO, and Hash.
  13. In PHP5 a new MySQL extension named MySQLi for developers using MySQL 4.1 and later.
  14. In PHP5, SQLite has been bundled with PHP.
Posted by Amit Tiwari

Monday 16 June 2014

How can we upload files in php.

If you want to upload any files in php.So first create the form by using <form></form> tag in php.

<html>
<body>
<form action="upload.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>









Now,for uploading we have to create script for "upload.php" file.


<?php
if ($_FILES["file"]["error"] > 0) {
  echo "Error: " . $_FILES["file"]["error"] . "<br>";
} else {
  echo "Upload: " . $_FILES["file"]["name"] . "<br>";
  echo "Type: " . $_FILES["file"]["type"] . "<br>";
  echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
  echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
?>


Using of PHP $_FILES array you can upload files from a client computer to the remote server.

The first parameter is the form's input name and the second index can be either "name", "type", "size", "tmp_name" or "error". Like this:

$_FILES["file"]["name"]       // the name of the uploaded file.
$_FILES["file"]["type"]       // the type of the uploaded file.
$_FILES["file"]["size"]       //  the size in bytes of the uploaded file.
$_FILES["file"]["tmp_name"]   //the name of the temporary copy of the file stored on the server.
$_FILES["file"]["error"]      // the error code resulting from the file upload.

You can also put restrictions on Upload-

In this script we add some restrictions to the file upload. The user may upload .gif, .jpeg, and .png files; and the file size must be under 40 kB:

<?php
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);

if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 40000)
&& in_array($extension, $allowedExts)) {
  if ($_FILES["file"]["error"] > 0) {
    echo "Error: " . $_FILES["file"]["error"] . "<br>";
  } else {
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Stored in: " . $_FILES["file"]["tmp_name"];
  }
} else {
  echo "Invalid file";
}
?>

Saving the Uploaded File-


<?php
             $allowedExts = array("gif", "jpeg", "jpg", "png");
             $temp = explode(".", $_FILES["file"]["name"]);
             $extension = end($temp);

if ((($_FILES["file"]["type"] == "image/gif")
            || ($_FILES["file"]["type"] == "image/jpeg")
            || ($_FILES["file"]["type"] == "image/jpg")
            || ($_FILES["file"]["type"] == "image/pjpeg")
            || ($_FILES["file"]["type"] == "image/x-png")
            || ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 40000)
&& in_array($extension, $allowedExts)) {
  if ($_FILES["file"]["error"] > 0) {
              echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
  } else {
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
    if (file_exists("upload/" . $_FILES["file"]["name"])) {
      echo $_FILES["file"]["name"] . " already exists. ";
    } else {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
    }
  }
} else {
  echo "Invalid file";
}
?>

The above script first checks if the file already exists, if it does not, it copies the file to a folder called "upload".


Posted by Amit Tiwari

Difference between include() & require()

Hello friend ..today i am going to teach you about the both { Include() & Require() } main functions in php.Both has same meaning but in a different manner.

Include() function

Syntax=include('main.php');

For this we have to create the file with extention of  ".php",

<?php
<body>
<a href="http://www.example.com/index.php">Home</a> <br />
<a href="http://www.example.com/about.php">About Us</a> <br />
<a href="http://www.example.com/services.php">Services</a> <br />
<a href="http://www.example.com/portfolio.php">Portfolio</a> <br />
<a href="http://www.example.com/Contact.php">Contact Us</a>
</body>
?>

Now ,save this file as main.php.for including this file we have to create new file called index.php. Here we know about the importance or we can say that how to use a include function,

<?php include("main.php"); ?>
<p>Hello this is my first php website</p>
</html>

Require() function-

Try the same example ,by using the function require() in the place of include().The only different is that require() function gives fatal error if there is no file found.

<?php include("nofile.php"); ?>
<p>Hello this is my first website</p>


Output=It gives fatal error and stop the script.








Posted by Amit Tiwari

Thankyou,

If you have any doubt related to post and want to know more about this so just comment in the below comment box,I ll response asap.


Friday 13 June 2014

PHP end() Function

Basically End function sets the pointer of an array to the last element of array.

Syntax-end(array)










For Example-



<?php
                $arr            =  array('name'=>'amit','age'=>'22','city'=>'bhopal','profession'=>'php developer');
                $lastValue   = end($arr);
?>

OUTPUT :  php developer

Posted Amit Tiwari

What is .htaccess?

.HTACCESS define as -

"It's a configuration file for use on web servers running the Apache Web Server software. When a .htaccess file is placed in a directory which is in turn 'loaded via the Apache Web Server', then the .htaccess file is detected and executed by the Apache Web Server software."


Use of .htaccess-

1) .htaccess file is basically used for url rewriting.
2) .htaccess file used to make the site password protected.


Below example show how we can use the htaccess file.

.htaccess
















Posted by Amit Tiwari


Tuesday 10 June 2014

Difference between strstr and stristr in php.

Functions strstr() and stristr, these are used to find the first occurence of the string (case-sensitive) but stristr() is case insensitive.

strstr() - Find first occurrence of a string.

Syntax:
                   strstr ($string, string) 

Example:

<?php
                  $email = 'makersofweb@rAls.com';
                  $domain_name = strstr($email, 'A);
                 echo $domain_name;

?>

Output:

Als.com



stristr() - Find first occurrence of a string (Case-insensitive)




















stristr ($string, string) 

Example:

<?php
                     $email = 'makersofwb@rAls.com';
                     $domain_name = stristr($email, 'A');
                     echo $domain_name;
 ?>


Output-
              akersofwb@rAls.com

Posted by Amit Tiwari



str_split() function

PHP : str_split() function-

"The str_split() function is define as it's splits a string into an array"

Syntax-

str_split(string_name, split_length)











For example-























Output-


Array ( [0] => W [1] => e [2] => l [3] => c [4] => o [5] => m [6] => e [7] => [8] => t [9] => o [10] => [11] => m [12] => a [13] => k [14] => e [15] => r [16] => s [17] => o [18] => f [19] => w [20] => e [21] => b [22] => . [23] => c [24] => o [25] => m) Array ( [0] => Welc [1] => ome [2] => to m [3] => aker [4] => sofw [5] => eb.c [6] => om )


Posted by Amit Tiwari




Sunday 8 June 2014

What is str_replace()

Definition-This function replace some characters with some other characters in a string , this function is case sensitive.

Syntax:- str_replace(find,replace,string);
                             find:-required,specifies the value to find.
                             replace:-required,specifies the value to replace the value in find.
                             string:-required,specifies the string to searched.
for examlpe:-
               <?php
                                 echo str_replace("amit","daniel","hello  amit");
                 ?>
 
Output:-     hello daniel












Posted by Amit Tiwari

Use of var_dump

This function called var_dump is basically used for displaying the value and type of one or more variables.

In my definition i simply define as "Var_dump=(value+type)"

Now,let see the syntax of var_dump.

Syntax-var_dump(variable1,variable2,.....nntimes);

For Example--In this i am using one float value and one boolean value ..

/* Float=2.5 & Boolean=True */

<?php
                $a=2.5;
               $b=true;
               var_dump($a,$b);
?>

 Output :     float(2.5)
                   bool(true)


Second Example-

Var_dump

























Posted by Amit Tiwari

@Facebook

What is array_flip ?

Hello friends today i am going to teach you about the Array_flip...It define as "The array_flip() function flips/exchanges all keys with their associated values in an array."

Now,we know about syntax of array_flip-

Syntax="array_flip(array);"

For example-

<?php
                         $arrayName    = array("course1"=>"Java","course2"=>"Android");
                         $new_array    = array_flip($arrayName);
                             print_r($new_array);
?>

OUTPUT :

Array
(
[Java]          => course1
[Android]    => course2
)

Posted by Amit Tiwari

@Facebook


Thursday 5 June 2014

Session & Cookies in php.


Session in php-

A “session” is set for maintaining the user data as the person is browsing through the site. A session is very useful in e-commerce websites, social networking sites etc. In PHP, session variables are used to set the sessions. Anything can be set / stored in a session like the user’s id, username, some encrypted password string etc.

A session is always stored in the server. You lose all the session data once you close your browser, as every time you re-open your browser, a new session starts for any website.

Example: $_SESSION[‘customer_name’] = ‘Amit’;


Cookies in php-



A “cookie” is however different from a session. It stores some information like the username, last visited pages etc. So that when the customer visits the site again, he may have the same environment set for him. You can store almost anything in a browser cookie.

A cookie is stored in the client’s browser.

Like, when you check the ‘Remember Password’ link on any website, a cookie is set in your browser, which exists there in the browser until manually deleted. So, when you visit the same website again, you don’t have to re-login.

But, it can also be problematic at times, if the user has blocked cookies in his browser and you have a shopping site that utilizes cookies to store the data. Then, that person will never be able to shop from your website.

setcookie("username", "John", time()+2400);

There are some basic points in  session and cookies that are following:-

1) Session are temporary and Cookies are parmanent.
2)  Session data is store on server while Cookies are store on user's computer.
3) Cookies contents can be easily modify but to modify Session contents is very hard.
4 ) Cookies could be save for future reference but Session couldn't when user close the browser Session data also lost.

Posted by Amit Tiwari


Array_multisort function in php.

Definition of "PHP array_multisort() Function"-

The array_multisort() function returns a sorted array. You can assign one or more arrays. The function sorts the first array, and the other arrays follow, then, if two or more values are the same, it sorts the next array, and so on.
String keys will be maintained, but numeric keys will be re-indexed, starting at 0 and increase by 1.

You can assign the sorting order and the sorting type parameters after each array. If not specified, each array parameter uses the default values.

Syntax of array_multisort-

array_multisort(array1,sorting order,sorting type,array2,array3...)

First Example -

<html>
<body>

<?php
                  $a=array("Dog","Cat","Horse","Bear","Zebra");
                 array_multisort($a);
                 print_r($a);
?>

</body>
</html>

Output-

Array ( [0] => Bear [1] => Cat [2] => Dog [3] => Horse [4] => Zebra )


 Second Example-


array_multisort

















Output-











Posted by Amit Tiwari (Facebook)



Why we use array_slice.

array_slice - ( ) Cut a specified slice of elements from an array-

Use of array_slice is basically returns the selected part of an array.The array_slice() array function in PHP will cut a specified slice of elements from an array. It can take up to four parameters, but only requires two parameters to operate at a basic level. Parameter one is the array you wish to manipulate. Parameter two is the offset(where you want the array to begin to be sliced from). Parameter three is the length into the array you wish to slice. Parameter four is set to "true" to preserve keys, or "false" to not preserve keys.

Syntax-

array_slice(array,start,length,preserve)

For Example-

<html>
<body>

<?php
                  $a=array("Html","Css","Php","Java","C++");
                   print_r(array_slice($a,2));
?>

</body>
</html>

Output-
Array ( [0] => Php[1] => Java[2] => C++)


Posted by Amit Tiwari (Facebook)

Difference Between array_merge & array_combine.

Posted by Amit Tiwari

Hello friends !!! Here i am going to teach you about the ( PHP: array_merge) & (PHP: array_combine).

PHP: array_merge-


array_merge merges the elements of one or more than one array such that the value of one array appended at the end of first array. If the arrays have same strings  key  then the later value overrides the previous value for that key .

<?php
             $array1 = array("course1" => "Amit","course2" => "Tiwari");
             $array2 = array(("course1" => "Amit","course3" => "Makersofweb");
             $result = array_merge($array1, $array2);
         print_r($result);
?>

Output :  

Array
(
[course1] => Amit
[course2] => Tiwari
[course3] => Makersofweb
)

PHP: array_combine-


<?php
                     $array1    = array("course1","course2");
                     $array2    = array(("Amit ","Tiwari");
                     $new_array = array_combine($array1, $array2);
print_r($new_array);
?>

Output :

Array
(
[course1]    => Amit
[course2]    => Tiwari
)

Note-If you like the above post like and share your views with me & have any doubt then comment in below comment box... Thanks !!!Facebook, Gplus

Difference Between UNSET & UNLINK.

Posted By Amit Tiwari

Hello friends there are two main functions used for deleting the file and destroy the variable.Namely UNLINK & UNSET.

Example for Unlink function:-

-The unlink() function deletes a file.
-This function returns TRUE on success, or FALSE on failure.

Syntax-

unlink(filename,context)








Code for this,



<?php
                    $file = "test.txt";
       if (!unlink($file))
            {
                                 echo ("Error deleting $file");
             }
else
             {
                                 echo ("Deleted $file");
             }
?>

Now,before starting to know about Unset we need to know about what is Php Session Variables.

PHP Session Variables-


When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state.

A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database.

Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.

Now..you can destroy the session means use of Unset function.
Follow the steps,

1)Start the session.
2)Storing a session variable.
3)Destroying a session.

Starting the Php session-


The "session_start() function" is placed before the <html> tag ..or we can say that this code is placed on the top of the file where you start coding for the website.

For Example,

<?php session_start(); ?>

<html>
<body>

</body>
</html>

Storing a Session Variable:-

<?php
              session_start();
// store session data
              $_SESSION['follower']=1;
?>

<html>
       <body>

<?php
//retrieve session data
                 echo "Facebook=". $_SESSION['follower'];
?>

</body>
</html>

Output-

Facebook=1

Destroying a Session:-

If you wish to delete some session data, you can use the unset() or the session_destroy() function.

<?php
session_start();
if(isset($_SESSION['follower']))
  unset($_SESSION['follower']);
?>

Or you can use directly the session destroy function..

<?php
session_destroy();
?>

Note: session_destroy() will reset your session and you will lose all your stored session data.

Posted by Amit Tiwari


WHo Is The Father Of PHP?

Posted By Amit Tiwari

Hello, Today I am going to inform you about the father of php ..who developed the server scripting language and in which year this is organized.

Rasmus Lerdford-Php was created by Rasmus Lerdorf In 1995.

-He was born in 22 November 1968,Qeqertarsuaq,Greenland.

-He created the PHP scripting language, authoring the first two versions of the language and participating in the development of later versions led by a group of developers including Jim Winstead (who later created blo.gs), Stig Bakken, Shane Caraveo, Andi Gutmans and Zeev Suraski. He continues to contribute to the project.


Education:-

He graduated from King City Secondary School in 1988, and in 1993 he graduated from the University of Waterloo with a Bachelor of Applied Science in Systems Design Engineering. He contributed to the Apache HTTP Server and he added the LIMIT clause to the MSQL DBMS. The LIMIT clause was later adapted by several other DBMS.

Awards:-

In 2003, he was named to the MIT Technology Review TR100 as one of the top 100 innovators in the world under the age of 35.

-Rasmus Lerdorf  @Twitter








Monday 2 June 2014

How php works?

Hello friends !!! Below image define as how the php works..


















Posted By Amit Tiwari

Wednesday 28 May 2014

What Is Variables In PHP?

Variables define as "Variable($)=Storing a value"
-All variables in PHP are denoted with a leading dollar sign ($)

-A variable is called as just a storage area. If you want to put value so you can store this value in variables,so that you can use and manipulate them in your programmes. Things you'll want to store are numbers and text.

Here are the most important things to know about variables in PHP:-


1) The value of a variable is the value of its most recent assignment.

2) Variables are assigned with the = operator, with the variable on the left-hand side and the expression to be evaluated on the right.

3) Variables can, but do not need, to be declared before assignment.

4) Variables in PHP do not have intrinsic types - a variable does not know in advance whether it will be used to store a number or a string of characters.

5) Variables used before they are assigned have default values.

6) PHP does a good job of automatically converting types from one to another when necessary.

7)  PHP variables are Perl-like.

PHP has a total of eight data types which we use to construct our variables:-
























Posted by Amit Tiwari

Sunday 25 May 2014

PhP Introduction By-Amit Tiwari

Hello Everyone today, I am going to teach you what is PhP & What is the use of php?......If you want to know all about this so you are in the right place..
This tutorial helps you to start your own codes and also for helping to create a website.

PHP Stands for -"Hyper Text Preprocessor"
Created by Rasmus Lerdorf in 1995.




What Can PHP Do?


-PHP can generate dynamic page content.
-PHP can create, open, read, write, delete, and close files on the server.
-PHP can collect form data.
-PHP can send and receive cookies.
-PHP can add, delete, modify data in your database.
-PHP can restrict users to access some pages on your website.
-PHP can encrypt data.
With PHP you are not limited to output HTML. You can output images, PDF files, and even Flash movies. You can also output any text, such as XHTML and XML.

What is the use of Php ?


-PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
-PHP is compatible with almost all servers used today (Apache, IIS, etc.)
-PHP supports a wide range of databases.
-PHP is free. Download it from the official PHP resource: www.php.net
-PHP is easy to learn and runs efficiently on the server side.

PHP Installation-




























Note-Hello my dear friends if you like this post and need to know something else so comment below in comment box.

Posted By-Amit Tiwari





Saturday 17 May 2014

What Is Database?

Database is define as it is a separate application that stores a collection of data. Each database has one or more distinct APIs for creating, accessing, managing, searching and replicating the data it holds.

Other kinds of data stores can be used, such as files on the file system or large hash tables in memory but data fetching and writing would not be so fast and easy with those types of systems.

So nowadays, we use relational database management systems (RDBMS) to store and manage huge volume of data. This is called relational database because all the data is stored into different tables and relations are established using primary keys or other keys known as foreign keys.

A Relational DataBase Management System (RDBMS) is a software that:


1) Enables you to implement a database with tables, columns and indexes.

2) Guarantees the Referential Integrity between rows of various tables.

3) Updates the indexes automatically.

4) Interprets an SQL query and combines information from various tables.

What is MySQL?

MySQL is very important or we can say that it's a main database used in PHP (Hyper Text Preprocessor)
For exmaple if we are creating a new website so that our all data means user informations like (mobile number,name,email etc) are stored in database in tabular form.

Various definition of MySQL are-



-MySQL is a database system used on the web
-MySQL is a database system that runs on a server
-MySQL is ideal for both small and large applications
-MySQL is very fast, reliable, and easy to use
-MySQL supports standard SQL
-MySQL compiles on a number of platforms
-MySQL is free to download and use
-MySQL is developed, distributed, and supported by Oracle Corporation.

More information about MySQL-



MySQL is a fast, easy-to-use RDBMS being used for many small and big businesses. MySQL is developed, marketed, and supported by MySQL AB, which is a Swedish company. MySQL is becoming so popular because of many good reasons:

1) MySQL is released under an open-source license. So you have nothing to pay to use it.

2) MySQL is a very powerful program in its own right. It handles a large subset of the functionality of the most expensive and powerful database packages.

3) MySQL uses a standard form of the well-known SQL data language.

4) MySQL works on many operating systems and with many languages including PHP, PERL, C, C++, JAVA, etc.

5) MySQL works very quickly and works well even with large data sets.

6) MySQL is very friendly to PHP, the most appreciated language for web development.

7) MySQL supports large databases, up to 50 million rows or more in a table. The default file size limit for a table is 4GB, but you can increase this (if your operating system can handle it) to a theoretical limit of 8 million terabytes (TB).

8) MySQL is customizable. The open-source GPL license allows programmers to modify the MySQL software to fit their own specific environments.


Note-Hello every one if you like this post please comment and share and want to know anything else related to mysql i ll help you.Thanks

Posted by Amit Tiwari

Thursday 15 May 2014

JavaScript If....Else Statements

JavaSript support the conditional statement which is used to perform the operation in a logical way.
Here in this post i teach you how the if \,ifelse and else if statements works or we can say that perform.


1) If Statement-


if (condition)

{

Statement(1) to be executed if condition is true

}

Here JavaScript expression is evaluated. If the resulting value is true, given statement(s) are executed. If expression is false then no statement would be not executed. Most of the times you will use comparison operators while making decisions.

Example-

<script type="text/javascript">
<!--
var age = 20;
if( age > 18 ){
   document.write("<b>Hello My Name Is Amit!</b>");
}
//-->
</script>

Output is 

Hello My Name Is Amit!

2) If....Else Statement-


Instead of using two if statement we ll commonly used if....else statement.
For Example-

if(condition)
{

Statement  to be executed if condition is true

}

else
{

Statement  to be executed if condition is false
}


Now by the below example you know how to use if....else statement during the codes.

<script type="text/javascript">
<!--
var age = 25;
if( age > 20 ){
   document.write("<b>Amit completed engineering.</b>");
}else{
   document.write("<b>Does not completed</b>");
}
//-->
</script>

Output-

Amit completed engineering.

3) if...else if... statement-


This statement is used for several condition.

if (condition){
   Statement to be executed if condition 1 is true
}
else if (condition 2)
{
   Statement to be executed if condition 2 is true
}
else if (condition 3)
{
   Statement to be executed if condition 3 is true
}
else
{
   Statement to be executed if no condition is true
}

The above is the syntax of if...else if statement now i am going to show the another example for this so that you know it easily and try to practice more time you get clear about all the statements.

Example-

<script type="text/javascript">
<!--
var book = "maths";
if( book == "history" ){
   document.write("<b>History Book</b>");
}else if( book == "maths" ){
   document.write("<b>Maths Book</b>");
}else if( book == "economics" ){
   document.write("<b>Economics Book</b>");
}else{
  document.write("<b>Unknown Book</b>");
}
//-->

</script>

Output-
Maths Book

Posted by- Amit Tiwari

Javascript Operators

What is an operator?

Operator are simple deifen as an example given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator.

Types of operators:-

-Arithmetic Operators

-Comparision Operators

-Logical (or Relational) Operators

-Assignment Operators

-Conditional (or ternary) Operators

Now hava look i am explaing the operators one by one,

1) Arithmetic Operators-
Assume variable A holds 10 and variable B holds 20 then

Operator Description Example
+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiply both operands A * B will give 200
/ Divide numerator by denumerator B / A will give 2
% Modulus Operator and remainder of after an integer division B % A will give 0
++ Increment operator, increases integer value by one A++ will give 11
-- Decrement operator, decreases integer value by one A-- will give 9


Note: Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give "a10".

2) Comparision Operators-

Assume variable A holds 10 and variable B holds 20 then
Operator Description Example
== Checks if the value of two operands are equal or not, if yes then condition becomes true. (A == B) is not true.
!= Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true.
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true.

3)Logical (or Relational) Operators-


Operator Description Example
&& Called Logical AND operator. If both the operands are non zero then then condition becomes true. (A && B) is true.
|| Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true. (A || B) is true.
! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is false.

4) Assignment Operators-


Operator Description Example
= Simple assignment operator, Assigns values from right side operands to left side operand C = A + B will assigne value of A + B into C
+= Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand C += A is equivalent to C = C + A
-= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand C -= A is equivalent to C = C - A
*= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand C *= A is equivalent to C = C * A
/= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand C /= A is equivalent to C = C / A
%= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand C %= A is equivalent to C = C % A

Note: Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=, &=, |= and ^=.

5) Conditional (or ternary) Operators -

There is one more operator called conditional operator. This first evaluates an expression for a true or false value and then execute one of the two given statements depending upon the result of the evaluation. The conditioanl operator has this syntax:

Operator Description Example
? : Conditional Expression If Condition is true ? Then value X : Otherwise value Y

Posted by Amit Tiwari

Javascript Reserved Words.

Javascript Reserved Words:-

The following are reserved words in JavaScript. They cannot be used as JavaScript variables, functions, methods, loop labels, or any object names.

abstract
boolean
break
byte
case
catch
char
class
const
continue
debugger
default
delete
do
double
else
enum
export
extends
false
final
finally
float
for
function
goto
if
implements
import
in
instanceof
int
interface
long
native
new
null
package
private
protected
public
return
short
static
super
switch
synchronized
this
throw
throws
transient
true
try
typeof
var
void
volatile
while
with

These are the reserved words in javascript.

JavaScript Variables and DataTypes:By Amit Tiwari

JavaScript DataTypes:-


There is the most fundamental characteristics of a programming language is the collection ofdata types it supports. These are the type of values that can be represented and manipulated in a programming language.

JavaScript always allows you to work with 3 primitive data types:


1)Numbers eg. 123456, 123.50 etc.

2)Strings of text e.g. "This text is string" etc.

3)Boolean e.g. true or false.

JavaScript also defines two trivial data types:


1)Null
2)Undefined,

Each of which defines only a single value.

In addition to these primitive data types, JavaScript supports a composite data type known as object.

Note: Java does not make a distinction between integer values and floating-point values. All numbers in JavaScript are represented as floating-point values. JavaScript represents numbers using the 64-bit floating-point format defined by the IEEE 754 standard.

JavaScript Variables:


Variable can have short names (like x and y) or more descriptive names (age, sum, totalVolume).

-Variable names must begin with a letter.
-Variable names can also begin with $ and _ (but we will not use it)
-Variable names are case sensitive (y and Y are different variables)





















The Scope Of JavaScript Variable.


The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes.

Global Variables: A global variable has global scope which means it is defined everywhere in your JavaScript code.

Local Variables: A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.

Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable. Following example explains it:


<script type="text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
   var myVar = "local";  // Declare a local variable
   document.write(myVar);
}
//-->
</script>

Output Is,




Note-In this above hope you get all the information about javascript variables and data types.If you have any doubt or if you want to ask something else ask freely just comment in comment box i ll response you asap.

Posted by Amit Tiwari

Javascript code placement in html file or document.

Hello everyone in this post i am going to teach you in how many ways you can put the javascript code in html file.


1) In head section or <head>........</head>
2)In body section or <body>.........</body>
3)In between head plus body.
4)Script that can be used as from the external source and this is inlcude in head section.


JavaScript in <head>...</head> section:


If you want to have a script run on some event, such as when a user clicks somewhere, then you will place that script in the head as follows:














JavaScript in <body>...</body> section:


If you need a script to run as the page loads so that the script generates content in the page, the script goes in the <body> portion of the document. In this case you would not have any function defined using JavaScript:















JavaScript in <body> and <head> sections:


You can put your JavaScript code in <head> and <body> section altogether as follows:


















JavaScript in External File :


As you begin to work more extensively with JavaScript, you will likely find that there are cases where you are reusing identical JavaScript code on multiple pages of a site.

You are not restricted to be maintaining identical code in multiple HTML files. The script tag provides a mechanism to allow you to store JavaScript in an external file and then include it into your HTML files.

Here is an example to show how you can include an external JavaScript file in your HTML code using script tag and its src attribute:














Posted by -Amit Tiwari

Javascript Enabling

Now a days all the popular browsers come with built-in support for JavaScript. Many times you may need to enable or disable this support manually.
In this post i will make you aware the steps of enabling and disabling JavaScript support in your browsers : Internet Explorer, Firefox, Chrome and Opera.

Javascript Enabling in chrome-

Launch Google Chrome from Start/Run with the parameter -enable-javascript. 


For example, in Vista: 
C:\Users\%username%\AppData\Local\Google\Chrome\Application\chrome.exe 

For example, in Windows XP: "C:\Documents and 
Settings\%username%\Local Settings\Application Data\Google\Chrome\chrome.exe" 
-enable-javascript 

or 

In my Windows XP it was here: "C:\Program Files\Google\Chrome\Application\chrome.exe" -enable-javascript 
NOTE: Javascript is supposed to be enabled in Chrome by default.
-enable-javascript

Javascript Enabling in firefox-

Steps to turn on or turn off JavaScript in your Firefox:

Follow Tools-> Options

from the menu
Select Content option from the dialog box

Select Enable JavaScript checkbox

Finally click OK and come out

To disable JavaScript support in your Firefox, you should not select Enable JavaScript checkbox.

Javascript Enabling in Internet Explorer-

Steps to turn on or turn off JavaScript in your Internet Explorer:

Follow Tools-> Internet Options from the menu

Select Security tab from the dialog box

Click the Custom Level button

Scroll down till you find Scripting option

Select Enable radio button under Active scripting

Finally click OK and come out

To disable JavaScript support in your Internet Explorer, you need to select Disable radio button under Active scripting.

Note-Please follow the above steps for your local browser if you want enabling.If you want any other help including this just mention in comment i ll provide the best solution for you.



Wednesday 14 May 2014

First Basic Program Using Javascript.

In this post you know about how we can write the simple program using javascript.


Program for printing "Hello Amit"


<html>
<body>
<script language="javascript" type="text/javascript">
<!--
   document.write("Hello Amit!")
//-->
</script>
</body>
</html>

We added an optional HTML comment that surrounds our Javascript code. This is to save our code from a browser that does not support Javascript. The comment ends with a "//-->". Here "//" signifies a comment in Javascript, so we add that to prevent a browser from reading the end of the HTML comment in as a piece of Javascript code.

Next, we call a function document.write which writes a string into our HTML document. This function can be used to write text, HTML, or both. So above code will display following result:

I am using dreamweaver so the code should be look like below image,



















Output is,








Just follow the above instruction an you are now able to write your code by own its easy just try once.if you are facing any doubt so ask freely i ll help you.Thanks

Javascript Syntax

The syntax of javascript is simple as like html.Only you have to start with the <script> tag and close with </script>tag.

For Example-

<script>

//(Javascript codes come in between this)

</script>


The script tag takes two important attributes:


language: This attribute specifies what scripting language you are using. Typically, its value will be javascript. Although recent versions of HTML (and XHTML, its successor) have phased out the use of this attribute.

Type: This attribute is what is now recommended to indicate the scripting language in use and its value should be set to "text/javascript".

So your JavaScript segment will look like:

<script language="javascript" type="text/javascript">
  JavaScript code
</script>


Note-By using the above code you can start your own code ...In my next post i ll teach you the first program with the help of javascript ...if you like then comment your views hoping best revert from your side. Thanks
:-)