MY mENU


Saturday 31 March 2012

Removing Unwanted Fonts


One trick that increases your boot time a bit is to lose any fonts in the Fonts folder in Control Panel that you never use. The more fonts you have, the more processing Windows XP has to do to prep all of those fonts for use. You must be a bit careful here to not remove fonts that you might want, but there is a good chance that you can live without many of them.
To delete unneeded fonts, follow these steps:
1. Open the Fonts folder in Control Panel.
2. Select Edit/Select All and then Edit/Copy.
3. Create a new folder on your desktop, open it, and select Edit/Paste.
4. In this new folder, delete any of the fonts you do not want.
5. Return to the Fonts folder in Control Panel. Right-click the selected fonts and click
Delete.
6. Go back to your new desktop folder and click Edit/Select All.
7. Return to your Fonts folder and click Edit/Paste. You now have only the desired
fonts in the Fonts folder.

Speed up IE Start Up


This tweak tells Internet Explorer to simply 'run', without loading any webpages. If you use a 'blank' page, that is still a page, and slows access. Notice the 'about:blank' in the address bar. The blank html page must still be loaded. To load IE with 'nothing' [nothing is different than blank]:
1. Right-click on any shortcut you have to IE
[You should create a shortcut out of your desktop IE icon, and delete the original icon]
2. Click Properties
3. Add -nohome [with a space before the dash] after the endquotes in the Target field.
4. Click OK

Disabling the Boot Logo


You can remove the boot logo that appears when you start Windows XP. This little tweak probably shaves only a few seconds off your boot time but seconds count if you are serious about trying to get Windows XP up and running as quickly as possible. The only negative is that if you remove the boot logo, you will also not see any boot messages, such as check disk.
To remove the boot logo, follow these steps:
1. Select Start/Run, type msconfig, and click OK.
2. In the System Configuration Utility, click the BOOT.INI tab.
3. On the BOOT.INI tab, click the NOGUIBOOT check box option. Click OK.

Disabling Recent Documents History


The bad thing about Recent Documents History is that Windows XP has to calculate what should be put there each time you boot Windows, which can slow things down.
1.  Open the Registry Editor (select Start/Run, type regedit, and click OK).
2.  Navigate to  HKEY_CURRENT_USER\Software\Mcft\Windows\CurrentVersion\Policies\Explorer.
3.  Create a NoRecentDocsHistory D_WORD key. Double-click the value to open it once it is created.
4.  Set the Data Value to 1 to enable the restriction.
5.  Click OK and close the Registry Editor. You'll need to restart the computer for the change to take effect.

Memory Tweak



  1. Start Registry Editor (Regedit.exe) and locate the following key in the registry:
  2. HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SessionManager\MemoryManagement\PrefetchParameters
  3. On the EnablePrefetcher value, change the setting from 3 to 5 (decimal).
  4. Close the registry editor and restart your computer

Stop Error Messages from Displaying on Startup


If you constantly see an error message that you can't get rid offer example, from a piece of software that didn't uninstall properly and continues to give errors on startup you can disable it from displaying on startup. Run the Registry Editor and go to HKEY_LOCALMACHINE\SYSTEM\CurrentControlSet\Control\Windows.
 (This key holds a variety of Windows system settings, such as the location of your system directory.) Create a new DWORD called NoPopupsOnBoot and give it a value of 1. Exit the Registry and reboot for the setting to take effect. To disable it, either delete the DWORD value or give it a value of 0.

Disabling Unused PORTS

I have just accidentally found out another way to give you an extra boost in windowsXP's boot performance. This is done by disabling your unused devices in Device Manager. for example, if you don't have input devices that are connected to one of your USBs or COM ports, disabling them will give you an extra perfromance boost in booting.

Go to Control Panel - System - Hardware tab - Device manager

Disable devices that you don't use for your PC and then restart. See the difference for yourself.

Perform a Boot Defragment: 

There's a simple way to speed up XP startup: make your system do a boot defragment, which will put all the boot files next to one another on your hard disk. When boot files are in close proximity to one another, your system will start faster. On most systems, boot defragment should be enabled by default, but it might not be on yours, or it might have been changed inadvertently.
            To make sure that boot defragment is enabled on your system, run the Registry Editor and go to:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Dfrg\BootOptimizeFunction

Edit the Enable string value to Y if it is not already set to Y. Exit the Registry and reboot. The next time you reboot, you'll do a boot defragment.

Stopping Unneeded Startup Services and Making XP boot faster !


Along with the core operating system and programs that Windows XP runs when it starts, there is also a host of services involved. Many of these services are necessary for Windows XP to operate correctly. However, many of them are for features in Windows XP that you may not use at all. You can peruse the services and disable any service that you do not want to run. The fewer services that run, the more quickly Windows XP will boot. To reduce the number of services that start on bootup, you can access two different areas of Windows XP.

1. The first is the System Configuration Utility. You can do that by entering the command “msconfig” in the run menu.
            Start  Run “msconfig” (without quotes) || Hit Enter

The Services tab shows you the services that start when the computer boots. You can stop a service from starting by simply clearing the check box next to the service and clicking OK.

2. Another way to disable services that you may prefer because the interface gives you more information about the service in question.

- Open Control Panel - Administrative Tools - Services or Start  Run “services.msc” || Hit Enter
- Take a quick look at common services you may want to live without:

Automatic Updates: This service enables Windows XP to check the Web automatically for updates. If you don't want to use Automatic Updates, you can disable the service.

Computer Browser: If your computer is not on a network, you don't need this service. If you are on a network, leave it alone.

DHCP Client: If you are not on a network, you do not need this service. If you are on a small workgroup, you can still increase boot time by configuring manual IP.

DNS Client: If you are not on a network, you do not need this service.

Error Reporting and Event Log: You don't have to use these services but they can be very helpful, so I would leave them configured as automatic.

Fax: If you don't use your computer for fax services, you can disable this one.

Help and Support: Disable if you never use the Windows XP Help and Support Center.

IMAPI CD-Burning COM: This service enables you to burn CDs on your computer.If you never burn CDs, you can disable the service without any second thoughts.

Indexing Service: Your computer keeps an index of all the files. But if you rarely search for files, the service is just a resource hog. You can stop it.

Windows Firewall/Internet Connection Sharing: If you do not use these features, plz disable.

Infrared Monitor: If you do not use infrared devices, you can disable this service.

Messenger: This service sends alert messages on a local area network (it is not the same as Windows Messenger). If you are not on a network, you can disable this service.

Print Spooler: If you do not do any printing from the computer, you can disable this service. If you print, make sure you leave it as automatic.

Remote Registry: This service allows remote users to modify the Registry on your computer. If you are not on a network, you can disable this service.

System Restore Service: This service allows you to use System Restore. If you have turned off System Restore anyway, you do not need to turn off the service.

Themes: If you do not use themes, you can disable this service.

Windows Image Acquisition: If you do not use scanners or digital cameras, you can disable.

Wireless Zero Configuration: If do not use wireless networking devices, you can disable.

Friday 30 March 2012

Writing the first JSP page

A JavaServer Page, technically speaking, is a web page which is embedded Java code. Java code is executed in the server side and merge with the static elements of the web page such as HTML tags... then returns the result which is plain old HTML code, JavaScript and CSS to the web browser.

This is the source code of our first JSP page which prints the simple famous greeting in programming world "Hello World" on the web browser.




JSP Page is composed of HTML and Java code. The Java code is embedded between thenotations <% and %> and it is called Scriptlet. Inside the scriptlet block, we call the method println of the out object to print the text "Hello World".

Thursday 29 March 2012

JSTL Types

JSP standard tags library can be divided into four tag libraries which are:
  1. Core tags
  2. Internationalization (i18l) and formatting tags
  3. Relational database access tags
  4. XML processing tags
The goals of those tag library above are:
  • Simplify the task of writing JSP page by providing friendly XML base tags
  • Provide reusable logic from page's presentation
  • Make the JSP page easier to read and maintain
Core tags:
As its name imply, core tags provide the core functionality actions to JSP to make the most common actions easier to achieve in a more effective way. Core tags specify several actions such as displaying content based on condition, manipulating collections and URL managing. By using the core tags you'll never has to write a such small piece of scriptlet. (But you still need to know scriptlet to maintain legacy web applications and convert them to JSTL later on if you have to).

Internationalization(I18L) and formatting tags:
Those tags specify a series actions to make the web application multilingual. Those actions including managing resource bundle, locales and base names.

Relational database access tags:
Accessing database is a most major task of web applications. JSTL provides a list of standard tags to help you to manipulate data such as select, insert, update and delete from the relational databases.

XML processing tags:
XML becomes a standard of enterprise web application for exchanging data. ManipulateXML effectively therefore is very important for most web applications and of course JSTL also provides a list of tags for processing from XML parsing to XML transformation.

Introducing to JSP Standard Tag Library - JSTL

JSP is designed for the presentation layer in the web applications but it needs to contain the logic or code inside the page to control the way it presents the visual elements. Since JSP was borned, scriptlet has been used intensively therefore the JSP pages become messy and difficult to maintain. The HTML mixed with JSP scriptlet and opening and closing brace make JSP page even hard to extend.

In June 2002, JavaServer Pages standard library (JSTL) specification 1.0 was first released. JSTL provided a new ways for JSP author to work with different elements with standard friendly tags. The current version of the JSTL is 1.2 which was started in 2004 so we will use JSTL 1.2 for all the tutorials.

JSP Advantages

  1. Separate the business logic and presentation: The logic to generate dynamic elements or content is implemented and encapsulated by using JavaBeans components. The user interface (UI) is created by using special JSP tags. This allows developers and web designers to maintain the JSP pages easily.
  2. Write Once, Run Anywhere: as a part of Java technology, JSP allows developers to develop JSP pages and deploy them in a variety of platforms, across the web servers without rewriting or changes.
  3. Dynamic elements or content produced in JSP can be served in a different formats: With JSP you can write web application for web browser serving HTML format. You can even produce WML format to serve hand-held device browsers. There is no limitation of content format which JSP provides.
  4. Take advantages of Servlet API: JSP technically is a high-level abstraction of Java Servlets. It is now easier to get anything you've done with Servlet by using JSP. Beside that you can also reuse all of your Servlets you've developed so far in the new JSP.

Introduction to JSP

JSP stands for JavaServer Pages. JSP is one of the most powerful, easy-to-use and fundamental technology for Java web developers. JSP combines HTML, XML, Java Servlet and JavaBeanstechnologies into one highly productivetechnology to allow web developers to develop reliable, high performance and platform independent web applications and dynamic websites.

Creating Threads in Java

Different ways to Create custom Threads in Java:
in java we can create user defined threads in two ways

  • Implementing Runnable Interface
  • Extending Thread class
in the both two approaches we should override run() method in sub class with the logic that should be executed in user defined thread concurrently, and should call start() method on Thread class object to create thread of execution in java Stacks area.

1. Extending the Thread class.::
class Mythread extends Thread {
                                  //method where the thread execution will start
public void run(){
                             //logic to execute in a thread
}
                               //let’s see how to start the threads
public static void main(String[] args){
Mythread t1 = new Mythread();
Mythread t2 = new Mythread();
t1.start();          //start the first thread. This calls the run() method.
t2.start();         //this starts the 2nd thread. This calls the run() method.
}
}

2. Implementing the Runnable interface.::
class MyRunnable extends Base implements Runnable{
                                      //method where the thread execution will start
public void run(){
                                     //logic to execute in a thread
}
                                    //let us see how to start the threads
public static void main(String[] args){
Thread t1 = new Thread(new MyRunnable());
Thread t2 = new Thread(new MyRunnable());
t1.start();                    //start the first thread. This calls the run() method.
t2.start();                   //this starts the 2nd thread. This calls the run() method.
}
}


In the first approach we create subclass object , Thread class object is also created by using its no-arg constructor. then when start method is called using subclass object custom thread is created in java stacks area, and its execution is started based on processor busy.

In the second approach when we create subclass object , Thread class object is not created, because it is not a subclass of Thread. so to call start method we should create thread class object explicitly by using Runnable parameter constructor, then using this Thread class object we should call start method. Then custom thread is created in Java stacks area and its execution is started based on processor busy.

Process And Thread

A process is an execution of a program but a thread is a single execution sequence within the process. A process can contain multiple threads. A thread is sometimes called a lightweight process.A JVM runs in a single process and threads in a JVM share the heap belonging to that process. That is why several threads may access the same object. Threads share the heap and have their own stack space. This is how one thread’s invocation of a method and its local variables are kept thread safe from other threads. But the heap is not thread-safe and must be synchronized for thread safety.


Definition of Thread:

  • A Thread is an independent sequential flow of execution/path.
  • A Thread is a stack created in java stacks area.
  • It executes methods in sequence one after one

When MultiThreading programming is suitable- means need of Multithreading?

- To complete independent multiple tasks execution in short time we should develop multithreading. In multithreading based programming CPU ideal time is utilized effectively.

Which class is extended by all other classes?

 - The Object class is extended by all other classes.

Can an object be garbage collected while it is still reachable? - A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected

When can an object reference be cast to an interface reference?

An object reference be cast to an interface reference when the object implements the referenced interface.

What is an object’s lock and which object’s have locks?

An object’s lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object’s lock. All objects and classes have locks. A class’s lock is acquired on the class’s Class object.

What is the difference between a static and a non-static inner class?

 A non-static inner class may have object instances that are associated with instances of the class’s outer class. A static inner class does not have any object instances.

Which Java operator is right associative?

 - The = operator is right associative.
- Can a double value be cast to a byte? - Yes, a double value can be cast to a byte.

What is the argument type of a program’s main() method?

A program’s main() method takes an argument of the String[ ] type.

What is the purpose of the finally clause of a try-catch-finally statement?

The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.

What is the difference between the Boolean & operator and the && operator?

 If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.

What is the purpose of finalization?

The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

An object’s finalize() method may only be invoked once by the garbage collector.

What are order of precedence and associativity?

- Order of precedence determines the order in which operators are evaluated in expressions.
- Associativity determines whether an expression is evaluated left-to-right or right-to-left

What is a native method?

 A native method is a method that is implemented in a language other than Java.

What is the difference between preemptive scheduling and time slicing?

 Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?

Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.

What modifiers may be used with an inner class that is a member of an outer class?

 A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.

What is synchronization and why is it important?

 With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often leads to significant errors.

Wednesday 28 March 2012

How do I convert a numeric IP address like 192.18.97.39 into a hostname like java.sun.com?

 String hostname = InetAddress.getByName("192.18.97.39").getHostNam

What does it mean that a method or field is “static”?

 Static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class. Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That’s how library methods like System.out.println() work. out is a static field in the java.lang.System class.

Why isn’t there operator overloading?

 Because C++ has proven by example that operator overloading makes code almost impossible to maintain. In fact there very nearly wasn’t even method overloading in Java, but it was thought that this was too useful for some very basic methods like print(). Note that some of the classes like DataOutputStream have unoverloaded methods like writeInt() and writeByte().

What are some alternatives to inheritance?

 - Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn’t force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).

What are the different identifier states of a Thread?

 - The different identifiers of a Thread are: 
   R          - Running or runnable thread, 
   S          - Suspended thread, 
  CW      - Thread waiting on a condition variable, 
  MW      - Thread waiting on a monitor lock, 
  MS       - Thread suspended waiting on a monitor lock

What is a local, member and a class variable?

 - Variables declared within a method are “local” variables.
-  Variables declared within the class i.e not within any methods are “member” variables (global         variables). 
-Variables declared within the class i.e not within any methods and are defined as “static” are class variables

What is Externalizable?

 - Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in)

Can an Interface have an inner class?

 - Yes.
 public interface abc
 {
  static int i=0; void dd();
  class a1
  {
   a1()
   {
    int j;
    System.out.println("inside");
   };
   public static void main(String a1[])
   {
    System.out.println("in interfia");
   }
  }
 }

What are the methods in Object?

 - clone, equals, wait, finalize, getClass, hashCode, notify, notifyAll, toString

What is composition? What is aggregation?

- Holding the reference of the other class within some other class is known as composition.


- It is a special type of composition. If you expose all the methods of a composite class and route the method call to the composite method through its reference, then it is called aggregation.

What is skeleton and stub? what is the purpose of those?

 - Stub is a client side representation of the server, which takes care of communicating with the remote server. 
   Skeleton is the server side representation. But that is no more in use… it is deprecated long before in JDK.

What is the purpose of assert keyword used in JDK1.4.x?

 - In order to validate certain expressions. It effectively replaces the if block and automatically throws the AssertionError on failure. This keyword should be used for the critical arguments. Meaning, without that the method does nothing.

What is reflection?

- Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes, and the use reflected fields, methods, and constructors to operate on their underlying counterparts on objects, within security restrictions.

What is the purpose of Void class?

 - The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the primitive Java type void.

Monday 26 March 2012

Operators in PHP


The most common PHP operators are 
  1. Assignment operators,
  2. Arithmetic operators, 
  3. combined operators, 
  4. comparison operators, 
  5. logical operators. 
  6. Relational Operators
  7. Increment and Decrement Operator
  8. Negation Operator
  9. Error Controlling operator
  10. String/Concatenation operator
  11. Conditional(or) Ternary Operator
  12. "new" Operator
  13. "instanceOf" operator
  14. Scope resolution operator
  15. Dereferencing operator


Assignment Operators
The basic assignment operator in PHP is "=". This means that the operand to the left of "=" gets set to the value to the right of "=".

Arithmetic Operators

OperatorExampleResult
+4 + 26
-4 - 22
*4 * 28
/4 / 22
%4 % 20
++x = 4; x++;x = 5
--x = 4; x--;x = 3



Combined Operators
You can combine an arithmetic operator with the assignment operator to form a combined operator. Combined operators are shown below:

OperatorExampleMeaning
+=y += xy = y + x
-=y -= xy = y - x
*=y *= xy = y * x
/=y /= xy = y / x
%=y %= xy = y % x


Comparison Operators

OperatorMeaning
==is equal to
!=is not equal to
>is greater than
>=is greater than or equal to
<is less than
<=is less than or equal to


Logical Operators

OperatorMeaning
||or
&&and
andand
oror
xorxor
!not



Relational Operators
= = = will check for the content and also for the type.
! = =  


Increment and Decrement Operator


++ and - -


Negation Operator


- multiplying with (-1)


Error Controlling Operator:


@   when prepended an expression, any warning messages that is being generated will gets suppressed.


A PHP application is associated with two types of runtime mistakes:

  • Warning - if  warning occurs, the rest of the Programme  will be executed.
  • A Fatal error - if a fatal error occurs the Programme gets terminated.
String/concatenation operators:

. or .=

Conditional / ternery operator:   ?:



Variables in PHP

Variable Types
Variables play an important role in PHP, as they are places for holding values. In PHP, there is no need to declare variables. Variable can hold eight different data types:
  •  bloolean,
  •  integer, 
  • float, 
  • string, 
  • array,
  •  object,
  •  resource, 
  • NULL.
PHP is a weakly typed language. This means that variable type varies depending on what is stored in the variable at the time. For example, if we have a variable $a, when $a = 0, $a is an integer type variable. If later we set $a = "New", then $a becomes a string type variable.

Variable Name:
A variable name always starts with a $, followed by a letter or an underscore. The rest of the variable name can be a letter, a number or an underscore.

For example, $dog is a valid variable name, while @dog is not (@dog does not start with a $).

Variables in PHP are case-sensitive. For example, $Employee and $employee are two different variables.

Variable Scope:
In most cases, variables are local in scope. This means that variables declared within a function cannot be accessed outside of the function, and variables declared outside of a function cannot be access within the function.

To make a variable global, it must either be declared as global specifically, or it must be accessed using the $GLOBALS array.

XMLHttpRequest Properties

  • onreadystatechange
    An event handler for an event that fires at every state change.
  • readyState
    The readyState property defines the current state of the XMLHttpRequest object.
    Here are the possible values for the readyState propery:
    StateDescription
    0The request is not initialized
    1The request has been set up
    2The request has been sent
    3The request is in process
    4The request is completed
    readyState=0 after you have created the XMLHttpRequest object, but before you have called the open() method.
    readyState=1 after you have called the open() method, but before you have called send().
    readyState=2 after you have called send().
    readyState=3 after the browser has established a communication with the server, but before the server has completed the response.
    readyState=4 after the request has been completed, and the response data have been completely received from the server.
  • responseText
    Returns the response as a string.
  • responseXML
    Returns the response as XML. This property returns an XML document object, which can be examined and parsed using W3C DOM node tree methods and properties.
  • status
    Returns the status as a number (e.g. 404 for "Not Found" and 200 for "OK").
  • statusText
    Returns the status as a string (e.g. "Not Found" or "OK").

XMLHttpRequest Methods

abort(): Cancels the current request.
getAllResponseHeaders(): Returns the complete set of HTTP headers as a string.
getResponseHeader( headerName ): Returns the value of the specified HTTP header.
open( method, URL )
open( method, URL, async )
open( method, URL, async, userName )
open( method, URL, async, userName, password )
: Specifies the method, URL, and other optional attributes of a request.

The method parameter can have a value of "GET", "POST", or "HEAD". Other HTTP methods, such as "PUT" and "DELETE" (primarily used in REST applications), may be possible

The "async" parameter specifies whether the request should be handled asynchronously or not . "true" means that script processing carries on after the send() method, without waiting for a response, and "false" means that the script waits for a response before continuing script processing.

send( content ): Sends the request.
setRequestHeader( label, value ) :Adds a label/value pair to the HTTP header to be sent.

XMLHTTPRequest

The XMLHttpRequest object is the key to AJAX. It has been available ever since Internet Explorer 5.5 was released in July 2000, but not fully discovered before people started to talk about AJAX and Web 2.0 in 2005.

XMLHttpRequest (XHR) is an API that can be used by JavaScript, JScript, VBScript and other web browser scripting languages to transfer and manipulate XML data to and from a web server using HTTP, establishing an independent connection channel between a web page's Client-Side and Server-Side.

The data returned from XMLHttpRequest calls will often be provided by back-end databases. Besides XML, XMLHttpRequest can be used to fetch data in other formats, e.g. JSON or even plain text.

Steps to Do Ajax Programming

1.A client event occurs
  • A JavaScript function is called as the result of an event
  • Example: validateUserId() JavaScript function is mapped as a event handler to a onkeyupevent on input form field whose id is set to "userid"
2. The XMLHttpRequest object is created
      

var ajaxRequest;   // The variable that makes Ajax possible!
function ajaxFunction(){
try{
               // Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
            // Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
                // Something went wrong
alert("Your browser broke!");
return false;
}
}
}
}
 

3. The XMLHttpRequest object is Configured
In this step we will write a function which will be triggered by the client event and a callback function processRequest() will be registered

function validateUserId() {
ajaxFunction();
  // Here processRequest() is the callback function.
ajaxRequest.onreadystatechange = processRequest;
if (!target) target = document.getElementById("userid");

var url = "validate?id=" + escape(target.value);
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
}

4. Making Asynchornous Request to the Webserver
Source code is available in the above piece of code. Code written in blue color is responsible to make a request to the web server. This is all being done using XMLHttpRequest objectajaxRequest

function validateUserId() {
ajaxFunction();
         // Here processRequest() is the callback function.
ajaxRequest.onreadystatechange = processRequest;
if (!target) target = document.getElementById("userid");
var url = "validate?id=" + escape(target.value);
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
}

Assume if you enter srinivas in userid box then in the above request URL is set to validate?id=srinivas

5. Webserver returns the result containing XML document
You can implement your server side script in any language. But logic should be as follows

  • Get a request from the client
  • Parse the input from the client
  • Do required processing.
  • Send the output to the client.
If we assume that you are going to write a servlet then here is the piece of code

public void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException
{
String targetId = request.getParameter("id");
if ((targetId != null) &&
!accounts.containsKey(targetId.trim()))
{
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("true");
}
else
{
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("false");
}
}
 

 6. Callback function processRequest() is called
The XMLHttpRequest object was configured to call the processRequest() function when there is a state change to the readyState of the XMLHttpRequest object. Now this function will recieve the result from the server and will do required processing. As in the following example it sets a variable message on true or false based on retruned value from the Webserver.
 

function processRequest() {
if (req.readyState == 4) {
if (req.status == 200) {
var message = ...;
}

7. The HTML DOM is updated
This is the final step and in this step your HTML page will be updated. It happens in the following way JavaScript technology gets a reference to any element in a page using DOM API
The recommended way to gain a reference to an element is to call.

document.getElementById("userIdMessage"),
     // where "userIdMessage" is the ID attribute
    // of an element appearing in the HTML document
JavaScript technology may now be used to modify the element's attributes; modify the element's style properties; or add, remove, or modify child elements. Here is the example

script type="text/javascrip
function setMessageUsingDOM(message) {
var userMessageElement = document.getElementById("userIdMessage");
var messageText;
if (message == "false") {
userMessageElement.style.color = "red";
messageText = "Invalid User Id";
} else {
userMessageElement.style.color = "green";
messageText = "Valid User Id";
}
var messageBody = document.createTextNode(messageText);
       // if the messageBody element has been created simple
      // replace it otherwise append the new element
if (userMessageElement.childNodes[0]) {
userMessageElement.replaceChild(messageBody, userMessageElement.childNodes[0]);
} else {
userMessageElement.appendChild(messageBody);
}
}
start body
div id="userIdMessage"
end of body

How to Define Ajax Programme


Steps of AJAX Operation

  1. A client event occurs
  2. An XMLHttpRequest object is created
  3. The XMLHttpRequest object is configured
  4. The XMLHttpRequest object makes an asynchronous request to the Webserver.
  5. Webserver returns the result containing XML document.
  6. The XMLHttpRequest object calls the callback() function and processes the result.
  7. The HTML DOM is updated

Browser support for Ajax

All the available browsers can not support AJAX. Here is the list of major browsers which support AJAX.
  • Mozilla Firefox 1.0 and above
  • Netscape version 7.1 and above
  • Apple Safari 1.2 and above.
  • Microsoft Internet Exporer 5 and above
  • Konqueror
  • Opera 7.6 and above
So now when you write your application then you would have to take care of the browsers who do not support AJAX.

NOTE: When we are saying that browser does not support AJAX it simply means that browser does not support creation of Javascript object XMLHttpRequest object.
 

Writing Browser Specific Code
 Simple way of making your source code compatible to a browser is to use try...catch blocks in your javascript.

Name: Time:  

In the above Javascript code, we try three times to make our XMLHttpRequest object. Our first attempt:
ajaxRequest = new XMLHttpRequest();

is for the Opera 8.0+, Firefox and Safari browsers. If that fails we try two more times to make the correct object for an Internet Explorer browser with:
 

ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");>

If that doesn't work, then they are using a very outdated browser that doesn't supportXMLHttpRequest, which also means it doesn't support Ajax.

Most likely though, our variable ajaxRequest will now be set to whatever XMLHttpRequeststandard the browser uses and we can start sending data to the server.