Custom Search

Friday, November 27, 2009

FOSS hosting sites

FOSS hosting sites
------------------
sf.net
http://sf.net/

google code
http://code.google.com/

ohloh
http://www.ohloh.net/

github
http://github.com/

assembla
http://www.assembla.com/

Savannah
http://savannah.gnu.org/

How Ajax Works -1

How Ajax Works -1
--------------------------
AJAX depends on XmlHttpRequest. It was originally added to Microsoft Internet Explorer 5 as an ActiveX object, and has since been added to other browsers as a built-in JavaScript object. XmlHttpRequest will submit a request to a web server where the enclosing page is stored and return the results so that they can be used within the web page that made the XmlHttpRequest request.

Originally, XmlHttpRequest was intended to retrieve XML documents from the server, but in actuality it can retrieve any content as long as it's text. You can then incorporate the results into your page using the DHTML techniques.

The first step in using XmlHttpRequest is creating the object.Internet Explorer and other browsers handle XmlHttpRequest differently, so you have to use the capability detection features. This also enables you to avoid running into problems with browsers that don't support XmlHttpRequest at all. Here's the code:

if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}

First I check to see whether the browser provides XmlHttpRequest as a property of the window object. If it does (as browsers other than Internet Explorer do), I use the new keyword to create a new XmlHttpRequest object. If it does not, I check to see whether the browser supports the ActiveXObject property of window. Only Internet Explorer provides that feature, so if that check returns true, I can create an XmlHttpRequest object using ActiveX. The XmlHttpRequest object, once created, works the same in all browsers that support it. Here's how you use it to retrieve information from the server:

request.onreadystatechange = processReadyStateChange;
request.open("POST", "remote.cgi", true);
request.send("user=test");

I'll explain the first line last. The second line is used to specify the request method and URL for the connection. The first argument, "POST" in this example, is the request method to use. You can use "GET" or "POST" here, just as you can with the action attribute of the <form> element. The second argument is the URL. Since the request must go to the server where the page resides, you can just use a relative or absolute URL. There's no need to specify the server or protocol. In this case, the script would submit the request to remote.cgi in the same directory as the page containing this code. The final argument specifies whether the request should be asynchronous, and can be either TRue or false. You'll almost certainly want to use true here all the time. If you don't set the request to be asynchronous, the browser will wait for the request to complete before letting the user do anything.

Once you've created the connection, you need to send data over the connection using the send() method. If you use the GET method, you can just use an empty string ("") here. If you use POST, you'll include the actual data to send with the request as the argument to the send() method. Once again, think about the request as a form submission. You can gather data from form elements on the page and pass it to send() to submit the form via XmlHttpRequest rather than submitting the form itself. The data passed to send() should be encoded using URL encoding. After the data is submitted, your script has to handle the response from the server. That's where the first line comes in. In order to deal with the response, you have to register a function to handle events associated with XmlHttpRequest. You'd think that you could just write some JavaScript to handle the results and put it in your script after the line that sends the data to the server, but that's not how XmlHttpRequest works. Remember that I mentioned that XmlHttpRequest can be used asynchronously. What that means is that once the script sends the request, your code can go on and do other things while the browser deals with handling the results of the request.

The browser processes the response by generating events. If you want to do anything with the results, you have to register a function as the handler for those events. If you wanted to register a handler for an onclick event for a link, you could use this code:
<a href="/" id="mylink" onclick="linkClicked()">My link</a>

There's another way to register a handler as well, entirely within a script. If you wanted to use JavaScript to register the event handler for the link, which I helpfully gave the ID mylink, you could do it like this:
document.getElementById("mylink").onclick = linkClicked;

One thing to note is that I don't include the () after linkClicked in the JavaScript example. That's because I want to associate the function named linkClicked with that event. If I include the parentheses, the script will actually call the function and assign the results to the onclick property. I want the function itself in this case.
OK, back to XmlHttpRequest. As I mentioned, the browser handles the response by generating events. I specified the handler for those events on this line:
request.onreadystatechange = processReadyStateChange;

That line says that onreadystatechange events for the XmlHttpRequest object should be passed to a function named processReadyStateChange. When a response is being processed, it goes through multiple states before it's finished.

Table : XmlHttpRequest States
State Description
0 --> The open() method has not been called.
1 --> The send() method has not been called.
2 --> The send() method has been called but the response headers have not been sent back.
3 --> Some response data has been received.
4 --> All of the response data has been received.

As you can probably guess, the states progress from 0 to 4. The function you associate with onreadystatechange is called every time the state advances. Here's what such a function looks like:
function onreadystatechange() {
if (request.readyState == 4) {
window.alert("Finished!");
}
}


This function examines the readyState property of the XmlHttpRequest object to see what the current state of the request is. This function will be called once for every state change, but it doesn't do anything until state 4 is reached and the request is finished. At that point, it just displays an alert. Most handlers will be written like this because the only state you care about is state 4. In addition to readyState, XmlHttpRequest has other properties, which are listed in below table.

Table : XmlHttpRequest Properties
Property Description
onreadystatechange --> The function specified to handle state change events
readyState --> The current ready state for the object
responseText --> The response sent by the server
status The --> HTTP status code of the response
statusText --> The text message associated with the HTTP status

Once you've reached readyState 4, you can access the data passed back from the server via the responseText property and deal with it as you wish.

An AJAX Example
-------------------------
In this example, I've created a page that allows you to update the current temperature by pressing a button. I use XmlHttpRequest to retrieve the current temperature, and use JavaScript to replace a <div> on the page with data from the server. Here's the source code for the page:

-----------------------test.html

<html xmlns="http://www.w3.org/1999/xhtml" version="-//W3C//DTD XHTML 1.1//EN"
xml:lang="en">
<head>
<title>AJAX Example</title>
<script language="JavaScript">
var request = false;

function sendAjaxRequest(toUrl) {
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}

if (request) {
request.onreadystatechange = processReadyStateChange;
request.open('GET', toUrl, true);
request.send("");
}
}

function updateTemperature(msg) {
var contentDiv = document.getElementById("ajaxTarget");
contentDiv.innerHTML = msg;
}

function getLatestTemp() {
sendAjaxRequest("temp.txt");
}

function processReadyStateChange() {
if (request.readyState == 4) {
if (request.status == 200) {
updateTemperature(request.responseText);
}
else {
alert("An error occurred.");
}
}
}
</script>
</head>

<body>
<p>
Current temperature:
<div id="ajaxTarget" style="font-size: x-large;">90 degrees</div>
</p>

<p>
<button onclick="getLatestTemp()">Update Temperature</button>
</p>
</body>
</html>

--------------------test.txt
55 degree

----------------------------
As you can see, the HTML section of the page is relatively short. All I have is a paragraph containing a <div> that contains the current temperature and another paragraph with a button that's used to update the temperature.
When the user clicks on the Update Temperature link, the function specified in the onclick handlergetLatestTemp()is called. That function contains a single line of code:
sendAjaxRequest("temp.txt");

This code just calls another function I wrote called sendAjaxRequest(). The argument is the URL for the content on the server. Ordinarily, the URL would point to a script that looks up the current temperature and transmits it back to the user. In this case, I have a text file on the server in the same directory as this page, and XmlHttpRequest is happy to retrieve it. The temp.txt file contains only the following text:
55 degrees

The code in the sendAjaxRequest() function should look familiar, since I just explained how it works. I create a new XmlHttpRequest object, assign a handler to the onreadystatechange event, open the connection, and send the request data. One thing you might notice is that I declare the request variable at the top level of my script rather than within my function. That's so that the variable is visible to the handler function as well as to the function where it is assigned.
I also test to make sure that my attempts to create the XmlHttpRequest object were successful prior to calling any of its methods. That way I won't produce errors in older browsers that don't support XmlHttpRequest. In this script, my event handling function does a lot more than the previous one. Here's the source:
function processReadyStateChange() {
if (request.readyState == 4) {
if (request.status == 200) {
updateTemperature(request.responseText);
}
else {
alert("An error occurred.");
}
}
}

As in the preceding code, the script only cares about readyState 4. It ignores all of the state changes leading up to it. Once readyState 4 has been reached, it checks the status property of the XmlHttpRequest object. A status of 200 means that the request was successful and the script received the text it wants. If the status is anything else, an error message is displayed. If the request was successful then the script calls the updateTemperature function, passing in the response text as an argument.
In this case, temp.txt contains only the temperature to be displayed. More involved scripts could produce complex data structures represented as XML that the page has to unpack, but in this example I just want to take the result and display it. That's what updateTemperature() is for:
function updateTemperature(msg) {
var contentDiv = document.getElementById("ajaxTarget");
contentDiv.innerHTML = msg;
}

The code uses the getElementById() function to obtain a reference to the <div> on the page. It then replaces its current contents with the response text using the innerHTML property.
As I said before, a real-life example would be significantly more complex, but this example illustrates how AJAX is used in a simple case. Unlike the other examples you've seen in this book so far, you'd have to put both the HTML page and temp.txt file on a web server in order for the example to work. XmlHttpRequest relies on the HTTP protocol, and its security constraints require the target to be on the same server as the page making the call.

====================================================

JavaScript Note -1

JavaScript Note -1
====================================================1
JavaScript "TextField" and "Radio Button" Validation
---------------------------------------------------------------------------
<script language="JavaScript">
<!-- start script here
function checkform(thisform)
{
if (thisform.name.value == null || thisform.name.value == "")
{
alert ("Please enter your name");
thisform.name.focus();
thisform.name.select();
return false;
}
var selected = false ;
for (var i = 0; i <= 2 ; ++i)
{
if (thisform.gender[i].status == true)
{
selected = true;
}
}
if (selected == false)
{
alert ("Please choose your sex");
return false;
}
return true;
}
// End of script -->
</script>

--------------------------------------------
</head>
<body>
<h1>Registration Form</h1>

<form action="/cgi-bin/register.cgi" method="post"
enctype="multipart/form-data" onsubmit="return checkform(this)">
<table>
<tr>
<td align="right" class="required"><b>Name:</b></td>
<td><input name="name" class="required" /></td>
</tr>
<tr>
<td align="right" class="required"><b>Gender:</b></td>
<td class="required">
<input type="radio" name="gender" value="male" /> male
<input type="radio" name="gender" value="female" /> female</td>
</tr>
<input type="submit" value="register" class="submit" />
</td>
</tr>
</table>
</form>
</body>
</html>

====================================================2
Creating an Image Rollover
----------------------------------------------
<html>
<head>
<title>JavaScript Rollover Example</title>
<script type="text/javascript" language="JavaScript">
<!--
// Preload the images for the rollover

if (document.images) {
buttonOn = new Image();
buttonOn.src = "on.gif";
buttonOff = new Image();
buttonOff.src = "off.gif";
}

// Function to replace the off images with on images.

function activate(image_name) {
if (document.images) {
document[image_name].src = eval(image_name + "On.src");
}
}

function deactivate(image_name) {
if (document.images) {
document[image_name].src = eval(image_name + "Off.src");
}
}
// -->
</script>
</head>
<body>
<a href="rollover.html" onmouseover="activate('button')"
onmouseout="deactivate('button')"><img name="button" border="0"
height="100" width="100" src="off.gif"></a>
</body>
</html>


====================================================3
DOM
---------
Modern web browsers create a representation of a page that can be accessed via scripts in a standardized fashion. This representation is called the Document Object Model, or DOM. Under the DOM, the page content is treated as a tree of objects. I'm using the word objects the way a software developer would. In that parlance, an object is a component that generally has different “properties”, “methods”, and “event handlers”. A property is data that somehow describes the object. A method is a function you can call to make the object do something or to manipulate the object itself. An event handler is a hook you can use to enable the object to respond to an action (generally an action performed by the user). If you were speaking grammatically, you'd say that properties are an object's nouns and methods are its verbs.
----------------------------------------------------------
DOM Data Types
-------------------
When a DOM representation of a web page is created, all of the objects that are used to construct the page are assigned to various categories, which are called “interfaces” in the world of object-oriented programming. If an object has a certain interface then it has the properties and methods associated with that interface. For example, all of the tags on a page have the “element interface”, which means that they support methods such as getAttribute and setAttribute.
Interfaces in the DOM

Data Type Purpose
---------------------
document This is the root object in the DOM.
node All of the other interfaces mentioned are children of the node interface, and express all of its properties and methods.
element All the tags on a page express the element interface, and thus inherit all its properties, methods, and event handlers.
nodeList An array (or list) of elements. Some method calls return lists of elements. For example, you can fetch all the items in a list or all the children of any element. The results are returned in a nodeList.
attribute Attributes of tags have their own interface.
NamedNodeMap An alternative form of list for dealing with groups of elements.

-----------------------------------------------------------
The base of the DOM tree is the “document” object. You can call methods of the document object directly, such as document.write() to add content to the page, or you can reference children of the document object, using methods such as getElementById() or getElementsByTagName().

Another object that you'll deal with frequently is “window”. The “window” object (unlike document) is not formally part of the DOM, but browsers include it in order to provide an interface to the browser itself. For example, the height and width of the browser window are properties of the window object rather than the document object.

Using generic methods, you can get to all the children of the document object, but a number of convenience methods are included to give you shortcuts to things such as the forms, images, and links on a page.

-------------------------------Example
In this example, we're going to create a web page that enables us to manipulate elements on a page in various ways using the DOM. This example will work in any modern browser that supports the DOM.
<html>
<head>
<title>DOM Example</title>
<script language="JavaScript">

function changeBgColor(newColor)
{
if (document.body)
{
eval('document.body.bgColor="' + newColor + '"');
}
}

function tackOn(headingText)
{
if (document.body)
{
if (headingText)
{
var newHeading = document.createElement("h1");
someText = document.createTextNode(headingText);
newHeading.appendChild(someText);
document.body.appendChild(newHeading);
}
}
}

function setHeadingColors()
{
var headings = document.getElementsByTagName("h1");

for (var i = 0; i < headings.length; i++)
{
headings.item(i).style.color = "yellow";
}
}

</script>
</head>
<body>

<form>
Background color:
<select onchange="changeBgColor(this.options[this.selectedIndex].value);">
<option value="white">white</option>
<option value="red">red</option>
<option value="blue">blue</option>
</select><br />

Add heading:
<input type="text" value="Spam" id="newHeading" />
<input type="button" value="tack it on"
onclick="tackOn(document.getElementById('newHeading').value);" />
<br />
<input type="button" value="change colors"
onclick="setHeadingColors();" />
</form>

</body>
</html>

Let me describe quickly how the page works. The form on the page enables you to change the page's background color, add new headings to the page, and set the color of all the headings currently on the page to yellow. We accomplish this using three JavaScript functions and five form fields.
====================================================4
Cross-Browser DHTML Techniques
--------------------------------------------------
The most common technique for creating cross-browser DHTML was detecting the user's web browser (commonly called sniffing). After you determined which browser the user was using, you could simply execute the code tailored to that browser.

Here's a relatively simple browser sniffer that detects only Netscape Navigator 4 and Microsoft Internet Explorer 4 and up.
The following example shows the browser sniffer in action. The body element of the web page calls the doSniff function, which in turn, creates a variable called sniff and assigns it a string value to display, depending on the browser version it detects.

<html>
<head>
<title>Browser Sniffing</title>
<meta http-equiv="Content-Script-Type" content="text/javascript" />

<script language="javascript" type="text/javascript">
<!-- Hide JavaScript

// Trimmed down browser sniffer that
// detects Navigator 4+ and IE 4+.
// Reference is_nav4up and is_ie4up in other
// portions of the script.
var agt = navigator.userAgent.toLowerCase();
var is_major = parseInt(navigator.appVersion);
var is_minor = parseFloat(navigator.appVersion);
var is_nav = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
&& (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
&& (agt.indexOf('Webtv')==-1));
var is_nav4up = (is_nav && (is_major >= 4));
var is_ie = (agt.indexOf("msie") != -1);
var is_ie4up = (is_ie && (is_major >= 4));


// Function to display the browser version
function doSniff() {
var sniff
if (is_nav4up == true) {
sniff = "Netscape Navigator 4+" }
if (is_ie4up == true) {
sniff = "Microsoft Internet Explorer 4+" }
alert(sniff);
}
// end hide -->
</script>
</head>
<body onload="doSniff()">
</body>
</html>

There are several big problems with relying on browser detection to make sure that your scripts work across multiple browsers. When new browsers are released, you have to go back through all your scripts that include browser detection and update them to account for the new browsers. Another problem is that if a browser you didn't account for supports the features included on your page, you might be denying access to people for no reason. Before you call a particular piece of code, you just have to test whether the browser supports the objects associated with the code you're calling.

====================================================5
Using JavaScript to Manipulate Elements
-----------------------------------------------------------------
In the world of Dynamic HTML, one of the most important tags you'll use is <div>. This tag is just a container into which you can put other elements. It's perfect because it enables you to group together some elements without any extra formatting baggage.

Once you've placed content within a <div> (or any other block level element), you can use JavaScript to manipulate its properties in the same way you set those properties when the page is displayed using CSS.
---------------------------------------------
One CSS property that is “visibility”,the two values for this attribute that you'll use are “hidden” and “visible”. Manipulating this property using JavaScript enables you to hide or reveal elements on a page.
I'm going to modify a page with the two overlapping elements so that if you click on one of the menus of links, the other is hidden.

<script language="JavaScript">
function hideMenu(idToHide)
{
if (document.childNodes)
{
document.getElementById(idToHide).style.visibility = 'hidden';
}
}
</script>

In the “hideMenu()” function, we first test for the presence of “document.childNodes”, which indicates that the browser has DOM support. If it does, we use “document.getElementById” to get a reference to the menu we want to hide, and I set the 'visibility' property to 'hidden'.


-------------------------------------------------------------
Creating a DHTML Pull-Down Menu
-----------------------------------------
It is possible to position elements on a page in a specific spot using style sheets. After they're positioned, you can move them around the page using JavaScript.
In this case, we've created a navigation bar across the top of the page. When the user puts the mouse pointer over the button in the navigation bar, the menu appears (and the button is highlighted). As long as the mouse pointer is over the button or the menu, the menu is displayed. Once the user removes the pointer, the menu will disappear after a 1-second delay.
<head>
<title>DHTML Test</title>
<script language="JavaScript">
function highlightAndPersist(button)
{
button.style.backgroundColor = '#ffc';
persist();
}
function unhighlight(button)
{
button.style.backgroundColor = '#ccf';
}

function persist()
{
var menu = document.getElementById('menu');
var button = document.getElementById('linkbutton');
menu.style.position = 'absolute';
menu.style.top = (button.offsetTop + button.offsetHeight) + 'px';
menu.style.left = (button.offsetLeft) + 'px';
menu.style.visibility = 'visible';
}

function hideSoon()
{
setTimeout("hide()", 1000);
}

function hide()
{
var menu = document.getElementById("menu");
menu.style.visibility = "hidden";
}
</script>

<style type="text/css">
body { margin: 0px; }
#menu
{
font-family: Verdana, sans-serif;
padding: 10px;
border: 1px solid black;
background-color: #ffc;
width: 150px;
visibility: hidden;
position: absolute;
top: 0px;
left: 0px;
}

#navbar
{
font: 18px Verdana, sans-serif;
width: 100%;
height: 30px;
background-color: #ccf;
padding: 0px;
}

.button
{
width: 80px;
height: 30px;
text-align: center;
}

p { margin: 10px; }
</style>
</head>
<body>
<div id="navbar">
<div id="linkbutton" class="button" onmouseover="highlightAndPersist(this);"
onmouseout="unhighlight(this);">
<b><a href="" onmouseover="persist();" onclick="return false;">Links</a></b>
</div>
</div>
<div id="menu" onmouseout="hideSoon();" onmouseover="persist();">
<a onmouseover="persist();" href="http://www.yahoo.com/">Yahoo</a><br />
<a onmouseover="persist();" href="http://www.salon.com/">Salon</a><br />
<a onmouseover="persist();" href="http://www.slashdot.org/">Slashdot</a><br />
</div>

<p>
Friends, Romans, countrymen, lend me your ears;<br />
</p>

</body>
</html>

The offsetTop, offsetLeft, and offsetHeight properties are available for any visual element on a page. I determine where to put the top of the menu by adding the height of the button to the top position of the menu. That places it immediately under the button. The left side of the menu should line up with the left side of the button, so I just used offsetLeft for the left position of the menu.

====================================================

Monday, November 16, 2009

Json Note-1

*****************************************

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language. JSON is a text format that is completely language independent.


JSON is built on two structures:

* A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
* An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.


1) An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).


2) An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).


3) A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.


4) A string is a collection of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string.


5) A number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.

**===========================** Example of JSON Object

var myJSONObject = {"employee": [
{"name": "saju", "age": "24", "place": "kollam"},
{"name": "manu", "age": "26", "place": "kottam"},
{"name": "praveen", "age": "28", "place": "trivandrum"}
]
};

In this example, an object is created containing a single member "employee", which contains an array containing three objects bindings[0],bindings[1], and bindings[2], each containing "name", "age", and "place" members.

Members can be retrieved using dot or subscript operators.

myJSONObject.bindings[0].place // "kollam"


{} ---> object
[] ---> Array
member:value ---> Key:value

**===========================**Convert a JSON text into an object

To convert a JSON text into an object, you can use the eval() function. eval() invokes the JavaScript compiler. Since JSON is a proper subset of JavaScript, the compiler will correctly parse the text and produce an object structure.

var myObject = eval('(' + myJSONtext + ')');

However, it can compile and execute any JavaScript program, so there can be security issues.So It is much safer to use a JSON parser.

A JSON parser will recognize only JSON text, rejecting all scripts. In browsers that provide native JSON support, JSON parsers are also much faster than eval. It is expected that native JSON support will be included in the next ECMAScript standard.

var myObject = JSON.parse(myJSONtext, reviver);

The optional reviver parameter is a function that will be called for every key and value at every level of the final result. Each value will be replaced by the result of the reviver function. This can be used to reform generic objects(int,float,date,string) into instances of pseudoclasses, or to transform Date strings into Date objects.

**===========================**Example of JSON parser

* JSON parser Converting JSON text into JSON Object.

myData = JSON.parse(text, function (key, value) {
var type;
if (value && typeof value === 'object') {
type = value.type;
if (typeof type === 'string' && typeof window[type] === 'function') {
return new (window[type])(value); <---- Creating the Object and return it.
}
}
return value;
});


OR


myData = JSON.parse(text,reviver(key,value));

function reviver(key, value) {
var type;
if (value && typeof value === 'object') {
type = value.type;
if (typeof type === 'string' && typeof window[type] === 'function') {
return new (window[type])(value); <---- Creating the Object of type of value and return it.
}
}
return value;
}

**===========================**Example of JSON stringifier

* JSON stringifier Converting JSON Object into JSON text (string format).

JSON does not support cyclic data structures, so be careful to not give cyclical structures to the JSON stringifier.

var myJSONText = JSON.stringify(myObject, replacer);

If the stringify method sees an object that contains a toJSON method, it calls that method, and stringifies the value returned. This allows an object to determine its own JSON representation.

The stringifier method can take an optional array of strings. These strings are used to select the properties that will be included in the JSON text.

The stringifier method can take an optional replacer function. It will be called after the toJSON method (if there is one) on each of the values in the structure. It will be passed each key and value as parameters, and this will be bound to object holding the key. The value returned will be stringified.

Values that do not have a representation in JSON (such as functions and undefined) are excluded.

Nonfinite numbers are replaced with null. To substitute other values, you could use a replacer function like this:

function replacer(key, value) {
if (typeof value === 'number' && !isFinite(value)) {
return String(value);
}
return value;
}

======================================

----------------------------------------

*****************************************

Saturday, November 14, 2009

Postgresql database initialization and Start in Debian

Postgresql database initialization and Start in Debian Linux

===================Solved=======================
Error:
createdb: could not connect to database postgres: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

================================================1
* Find the location of "initdb" binary and run it with -D option and directory "data" where we want to install datas of postgres database.For that run the following command.

root@localhost:~# su postgres -c "/usr/lib/postgresql/8.3/bin/initdb -D /usr/lib/postgresql/8.3/data"

could not change directory to "/home/root"
The files belonging to this database system will be owned by user "postgres".
This user must also own the server process.

The database cluster will be initialized with locale en_US.UTF-8.
The default database encoding has accordingly been set to UTF8.
The default text search configuration will be set to "english".

creating directory /usr/lib/postgresql/8.3/data ... initdb: could not create directory "/usr/lib/postgresql/8.3/data": Permission denied

================================================2
* change the permission of "/usr/lib/postgresql/"
if we could not create directory "/usr/lib/postgresql/8.3/data"

root@localhost:~# chmod -R 777 /usr/lib/postgresql/

================================================3
* Running the above command again.

root@localhost:~# su postgres -c "/usr/lib/postgresql/8.3/bin/initdb -D /usr/lib/postgresql/8.3/data"

could not change directory to "/home/root"
The files belonging to this database system will be owned by user "postgres".
This user must also own the server process.

The database cluster will be initialized with locale en_US.UTF-8.
The default database encoding has accordingly been set to UTF8.
The default text search configuration will be set to "english".

creating directory /usr/lib/postgresql/8.3/data ... ok
creating subdirectories ... ok
selecting default max_connections ... 100
selecting default shared_buffers/max_fsm_pages ... 24MB/153600
creating configuration files ... ok
creating template1 database in /usr/lib/postgresql/8.3/data/base/1 ... ok
initializing pg_authid ... ok
initializing dependencies ... ok
creating system views ... ok
loading system objects' descriptions ... ok
creating conversions ... ok
creating dictionaries ... ok
setting privileges on built-in objects ... ok
creating information schema ... ok
vacuuming database template1 ... ok
copying template1 to template0 ... ok
copying template1 to postgres ... ok

WARNING: enabling "trust" authentication for local connections
You can change this by editing pg_hba.conf or using the -A option the
next time you run initdb.

Success. You can now start the database server using:

/usr/lib/postgresql/8.3/bin/postgres -D /usr/lib/postgresql/8.3/data
or
/usr/lib/postgresql/8.3/bin/pg_ctl -D /usr/lib/postgresql/8.3/data -l logfile start

root@localhost:~#

================================================4
* start the database server.

root@localhost:~# su postgres -c "/usr/lib/postgresql/8.3/bin/postgres -D /usr/lib/postgresql/8.3/data"

LOG: database system was shut down at 2009-11-07 00:37:47 EST
LOG: autovacuum launcher started
LOG: database system is ready to accept connections
FATAL: database "root" does not exist
FATAL: database "saju" does not exist

================================================5
* take a new terminal and type following command.

saju@localhost:/home/root$ psql -U postgres

could not change directory to "/home/root"
Welcome to psql 8.3.6, the PostgreSQL interactive terminal.

Type: \copyright for distribution terms
\h for help with SQL commands
\? for help with psql commands
\g or terminate with semicolon to execute query
\q to quit

postgres=#

================================================6
* To solve phpPgAdmin Login Problem 'Login disallowed for security reasons' set $conf['extra_login_security'] to false;.
* To solve postgres user login problem 'Login disallowed for security reasons' in phpPgAdmin.

vim /var/www/phpPgAdmin/conf/config.inc.php

$conf['extra_login_security'] = false;


================================================7
* To access postgres database from terminal.

periyar:~# psql dbname -U username

Welcome to psql 8.3.6, the PostgreSQL interactive terminal.

Type: \copyright for distribution terms
\h for help with SQL commands
\? for help with psql commands
\g or terminate with semicolon to execute query
\q to quit

dbname=#

================================================8
* Postgresql database Backup and Restore commands.

Postgresql database backup command.
----------------------------------
#pg_dump -d shopdb -U username -f /home/user/shopdbbkp.txt


Postgresql database restore command.
-----------------------------------
#create database shopdb
#psql shopdb -U username -f /home/user/shopdbbkp.txt

================================================

Ajax Note-2

AJAX Note-2
-----------------------------
In this AJAX tutorial we don’t using JavaScript framework JQUERY and JSON. Instead we use JavaScript and XML.

************************************************* (A)
A
*************************************************1
Asynchronous JavaScript + XML

Best example of Ajax is Goggle Maps.

------------------------------------------------------

Ajax is not a technology. It is really several technologies.

* Standards-based presentation using XHTML ans CSS.
* Dynamic display and interaction using the Document Object Model.
* Data interchange and manipulation using XML and XSTL.
* Asynchronous data retrieval using XMLHttpRequest.
* and JavaScript binding everything together.

------------------------------------------------------

'Jasee James’ Model of AJAX.

AJAX applications are made up with 5 parts

1) User Interface ----> XHTML and CSS (Any web browser can display it).

2) DOM (Document Object Model)
The User Interface will have to change when the application runs, that is display new information’s or responds to user input. These changes in the User Interface made using the DOM (Document Object Model).
DOM is a "programming interface" for modifying a web page while it display in the browser.

3) XML
Ajax Applications needs send and receive information’s to and from the Web Server. That information is transmitted in XML format.

4) XMLHttpRequest
This is an object supported by most browsers that allows an application to make a request to the Web Server, receive response and process that response with out interrupting what user is doing.

5) JavaScript
JavaScript ties all the above 4 components together.

a) (JavaScript + XHTML and CSS) JavaScript monitor the 'users interaction' with the 'page' to 'determine' when something need to happened.

b) (JavaScript + XMLHttpRequest) JavaScript Create and activate XMLHttpRequest object to communicate with the Web Server.

c) (JavaScript + XML) JavaScript packages up the information’s to be send to the Web Server in XML format and extract the XML response that come back from the Web Server.

d) (JavaScript + DOM) JavaScript uses the DOM to modify the page currently displayed, thus inform the user that some thing is happened.

------------------------------------------------------

Above is the 'Jasee James' simple model of AJAX. But there are many other ideas or model for AJAX. Many people have many good ideas to improve the simple model of AJAX. For Example,

a) DOM or innerHTML
The standard "DOM" supported by many browsers is also happened to be slow in May browsers. But the nonstandard "innerHTML" supported by many browser happened to be faster than DOM.
The "innerHTML" allow the developer to just drop whole new block of HTML in to the page, the browser will display it with out disturbing the rest of the page.
So "innerHTML" is a good choice to modify the User Interface when the application runs.

b) XML or Plain Text or HTML or JSON
For transmitting messages to and from the Web Server using XML because it is supported by many programming languages.
But Most browsers can red and write XML,but it is slow and heavy process.
We can send data in many other ways....
Sending data as text
Sending a chunk of HTML that can be directly dropped into the page for display.
Sending JavaScript code that can be executed in order to get the information’s contained in the message.

c) XMLHttpRequest is a strong option to send request to Web Server.
Using this XMLHttpRequest object we can send multiple asynchronous requests and deal with responses if when they come.
The limitation of XMLHttpRequest is it only allows sending request to the same Web Server that send the web page currently being displayed.
But this is not a limitation and is used for security purposes.

d) XHTML and CSS or Flash or SVG or XUL
Several AJAX web applications not only using XHTML and CSS to create User Interfaces, instead they using
SVG ---> Scalable Vector Graphic.
XUL ---> Extensible User Interface Language.

Every AJAX applications using JavaScript in some forms ot other to send request in background to Web Server or modify User Interface in the front end. So learn JavaScript to learn AJAX

Every AJAX applications that widely using today deviate from Jessi James vision or model of AJAX in some way or other.
So mastering in AJAX is not only learning a limited set of technology. But also about learning when to use or select one option based on performance, browser compatibility, accessibility and standard.

------------------------------------------------------
AJAX developers must using Firebug.

Use Firebug's "Console"' option to monitor the AJAX request goes on in the background.
Here we can see the AJAX request made in the background by JavaScript to Web Server.
Here we can also see the Response coming back from the Web Server.
------------------------------------------------------
*************************************************2
XMLHttpRequest
==============================

* JavaScript respond to user interactions (on click, on change, on submit, etc) by sending request to Web Server in the background with an object called XMLHttpRequest.

* In order to tie up JavaScript to a particular html tag to respond to user interactions (on click, on change, on submit, etc) we need to make that html tag more identical by using either ID or CLASS attribute of html tag. Then the JavaScript code can take care on this html tag for user interactions (on click, on change, on submit, etc).

* We can use PHP script, Java, Perl, Python, Ruby etc for generating Response for request send by the JavaScript using object called XMLHttpRequest.

* Always try to keep JavaScript code in separate *.js file, that keep readability and accessibility of the page.

==============================
------------------------------------------------------1

* When loading web page we using some JavaScript code to find particular html tags using ID or CLASS attribute of html tag. In the past we used “window.onload“ Event Handler function .But because each document can only have one “window.onload“ Event Handler we need to write multiple scripts for it. We can solve this problem by using “Load” Listener instead of “window.onload“ Event Handler .A single document can have multiple “Load” Listeners associated with it. But the codes require to creating “Load” Listeners vary from browser to browser. A Solution for this is to use a function that contain codes require to creating “Load” Listeners for all popular browsers. We can copy updated version this function from internet. A copy of this function is as follows:

Here argument of this function is another JavaScript function.

function addLoadListener(fn)
{
if (typeof window.addEventListener != ‘undefined’)
{
window.addEventListener(‘load’,fn,false);
}
else if (typeof document.addEventListener != ‘undefined’)
{
document.addEventListener(‘load’,fn,false);
}
else if (typeof window.attachEvent != ‘undefined’)
{
window.attachEvent(‘onload’,fn);
}
else
{
var oldfn = window.onload;
if (typeof window.onload != ‘function’)
{
window.onload = fn;
}
else
{
window.onload = function()
{
oldfn();
fn();
};
}
}
}

------------------------------------------------------2

* Adding Load Listener to page.

addLoadListener(initAjaxTest);

* When the page finish it’s loading the function “initAjaxTest” will be called. So we need to create that function “initAjaxTest” .This function “initAjaxTest” is used for pick out particular html tags using ID or CLASS attribute of html tags from the web page or Document.


function initAjaxTest()
{
//Getting all INPUT tags from the Document and storing in array ‘inputNodes’.
var inputNodes = document.getElementsByTagName(‘input’);

for (var i=0;i<inputNodes.length;i++)
{

//Checking for INPUT tag with CLASS attribute name ‘buttonsubmit1’.
if(inputNodes[i].className = ‘buttonsubmit1’)
{
//Calling function ‘ajaxsubmit’ when clicking on that tag.
inputNodes[i].onClick = ajaxsubmit;
}
}
}

------------------------------------------------------3

When the user click on this tag the function “ajaxsubmit” will be calling. This function send request in background to Web Server, For that this function using XMLHttpRequest object.

function ajaxsubmit()
{
var xhr = new XMLHttpRequest(); //Creating XMLHttpRequest object ‘xhr’.

// This ‘xhr’ object allow to create request and send to the server and receive the response and do what ever you want with it.
// Microsoft Internet explorer 5 and 6 not support to create XMLHttpRequest object this way.
//So using another method to get support of Internet explorer 5 and 6.
}

------------------------------------------------------

Rewriting the code to get support of Microsoft Internet explorer 5 and 6.

function ajaxsubmit()
{
var xhr;

try
{
//Creating XMLHttpRequest object ‘xhr’, common way.
xhr = new XMLHttpRequest();
}
catch(error)
{
//if faille use Microsoft Internet explorer way to create XMLHttpRequest object.
try
(
xhr = new ActiveXObject(‘Microsoft.XMLHTTP’)
}
catch(error)
{
//if faille we can not create XMLHttpRequest object, so store NULL to ‘xhr’.
xhr = NULL;
}

if(xhr != NULL)
{
//if XMLHttpRequest object is created OR browser support AJAX.

// Here we writing the code to send request to Web Server using XMLHttpRequest object ‘xhr’. It is a 3 steps process.

//First step is call XMLHttpRequest object’s “open” method.
//Second step is set up a “onreadystatechange” Event Handler function,. this function is called every time the state of the request is updated.
// Third step is call XMLHttpRequest object’s “send” method.


// 1
xhr.open();


// 2
xhr.onreadystatechange = function()
{

};


// 3
xhr.send();


//return false means we don’t have to submit the form for browsers have AJAX support.
return false;

}

//if xhr is NULL ,that is no XMLHttpRequest object is created ,so we need to submit the form as usual because browser does not support AJAX, so we return true, so the page work with out using AJAX,

return true;

}

------------------------------------------------------4

Above code without comment and code for sending request and handling response using XMLHttpRequest object.


function ajaxsubmit()
{
var xhr;

try
{
xhr = new XMLHttpRequest();
}
catch(error)
{

try
(
xhr = new ActiveXObject(‘Microsoft.XMLHTTP’)
}
catch(error)
{
xhr = NULL;
}

if(xhr != NULL)
{
//if XMLHttpRequest object is created OR browser support AJAX.
// Here we writing the code to send request to Web Server using XMLHttpRequest object ‘xhr’. It is a 3 steps process.
//First step is call XMLHttpRequest object’s “open” method.
//Second step is set up a “onreadystatechange” Event Handler function, this function is called every time the state of the request is updated.
// Third step is call XMLHttpRequest object’s “send” method.

// 1
//The “open” method takes three arguments.
//First argument is the type of the request (POST or GET).
//Second argument is the URL where the request wants to go to.
// for security reason the URL can only be on the same Web Server that the current page that requested from. That is only tried to send request to files that generate and send response on the same Web Server where the requesting page exist, for security reason.
//We can append value with URL and send to Web Server for processing and send response back.
//In URL ’user/display/ajax/1’ we used ‘ajax/1’ to indicate the request handling code or page that it is an AJAX request and handle separate from normal POST and GET request and return separate response. Using this technique we can run the same web application in AJAX supported browser and nor supported browsers. Here “display” is the file or function which handles the request and sends response back.
// Third argument indicate whether the request should be synchronous or asynchronous. Use “true” means asynchronous that is request will be handled in the background with out interrupting the page.

xhr.open(‘POST’,’user/display/ajax/1,true);

// 2
//The “onreadystatechange” Event Handler function used to update User Interface with response from the Web Server.
//This function is called every time when we send request to Web Server with “send” method and this function update with status of the request.

// Ajax requests go through number of ready states as it progresses.
// Here “readyState” and “status” are properties or member variables of the XMLHttpRequest object ‘xhr’.
//If readyState ==4 indicate request completed.
//If status==200 || status=304 indicate request completed successfully and we can update User Interface.

xhr.onreadystatechange = function()
{

if(xhr.readyState == 4)
{
//Request completed

if(xhr.status==200 || xhr.status=304)
{
//Request completed successfully and we can update User Interface
//Code to update User Interface with new information’s received from the web Server writes here.
// --------//
//--------//
//--------//
}
else
{
//Request completed with failure

}

};


// 3
// The “send” method takes one argument which is the contents of the request.
// Suppose we using AJAX for submit form which contain some fields , then all of the field name and its values are encoded into a string and pass as argument of “send” method.
//This method is used to pass large number of contents with request.
//If we included the contents with URL of the “open” method, then no need to pass it as argument of “send” method, and pass “null” argument in that case.

xhr.send(null);


return false;

}

return true;

}

------------------------------------------------------5

Important Steps for creating AJAX applications

1) Binding an Event Handler
inputNodes[i].onClick = ajaxsubmit;

2) Creating an XMLHttpRequest object.
xhr = new XMLHttpRequest();

3) Send request to the Web Server.
xhr.open(‘POST’,’user/display/ajax/1,true);
xhr.send(null);


4) Keep track of request status
xhr.onreadystatechange = function()
{

if(xhr.readyState == 4)
{
//Request completed

if(xhr.status==200 || xhr.status=304)
{
//Request completed successfully and we can update User Interface
//Code to update User Interface with new information’s received from the web Server writes here.
// --------//
//--------//
//--------//
}
else
{
//Request completed with failure
}
};

These are the unique elements that make AJAX applications.

------------------------------------------------------6

Complete JavaScript code without comment.


function addLoadListener(fn)
{
if (typeof window.addEventListener != ‘undefined’)
{
window.addEventListener(‘load’,fn,false);
}
else if (typeof document.addEventListener != ‘undefined’)
{
document.addEventListener(‘load’,fn,false);
}
else if (typeof window.attachEvent != ‘undefined’)
{
window.attachEvent(‘onload’,fn);
}
else
{
var oldfn = window.onload;
if (typeof window.onload != ‘function’)
{
window.onload = fn;
}
else
{
window.onload = function()
{
oldfn();
fn();
};
}
}
}


addLoadListener(initAjaxTest);


function initAjaxTest()
{
var inputNodes = document.getElementsByTagName(‘input’);

for (var i=0;i<inputNodes.length;i++)
{

if(inputNodes[i].className = ‘buttonsubmit1’)
{
inputNodes[i].onClick = ajaxsubmit;
}
}
}


function ajaxsubmit()
{
var xhr;

try
{
xhr = new XMLHttpRequest();
}
catch(error)
{

try
(
xhr = new ActiveXObject(‘Microsoft.XMLHTTP’)
}
catch(error)
{
xhr = NULL;
}

if(xhr != NULL)
{
//if XMLHttpRequest object is created OR browser support AJAX.

// 1
xhr.open(‘POST’,’user/display/ajax/1,true);

// 2
xhr.onreadystatechange = function()
{

if(xhr.readyState == 4)
{
//Request completed

if(xhr.status==200 || xhr.status=304)
{
//Request completed successfully and we can update User Interface
// --------//
// --------//
}
else
{
//Request completed with failure
}
};

// 3
xhr.send(null);

return false;
}

return true;
}

------------------------------------------------------
*************************************************3
Server side code and how it response to AJAX requests.
--------------------------------------------------------------------------------

* Server side code only send the required information to browser (JavaScript Code) to update the page, not load the whole page.
* Server side code needs to send response to 'AJAX request' made by the JavaScript Code.
* We need to send the response in a format that the JavaScript Code can easily use to update the current page.

* There are number of choices to send Response back to JavaScript Code.
1) Most common choice currently is JSON which involves sending the data in the format of JavaScript code and JavaScript is grate to deal JavaScript.
2) We can send Response in plane text format and JavaScript red that plane text and update the page based on it.
3) Another choice is XML. That is sending Response to JavaScript in XML format.

===========================================
Example of Sending Response to JavaScript in XML format.
------------------------------------------------------------------------------------

* First create a PHP script that send contents to JavaScript in XML format.

<?php
header('content-type: text/xml');
echo '<?xml version="1.0" encoding="utf-8" ?>';
?>
<employee>

<?php foreach( $rows as $row){ ?>
<name> <?php echo $row['name']; ?> </name>
<age> <?php echo $row['age']; ?> </age>
<place> <?php echo $row['place']; } ?> </place>

</employee>

* Save this file with *.php extension.
* Then write JavaScript code to read this XML response and update the web page (user interface).

===========================================================
Example of JavaScript code to read this XML response and update the web page
--------------------------------------------------------------------------------------------------------------------


------------------------------------------------------


------------------------------------------------------
************************************************* (B)
B
*************************************************AJAX Example-1
AJAX Example - URL Preview using AJAX
------------------------------------------------------ Html code
<html>
<head>
<title>Smart Ajax Links</title>
<link rel="stylesheet" rev="stylesheet" href="script.css" />
<script src="script.js" type="text/javascript">
</script>
</head>
<body>
<h2>A Gentle Introduction to JavaScript</h2>
<ul>
<li><a href="jsintro/2000-08.html">August article</a></li>
<li><a href="jsintro/2000-09.html">September article</a></li>
<li><a href="jsintro/2000-10.html">October article</a></li>
<li><a href="jsintro/2000-11.html">November article</a></li>
</ul>
<div id="previewWin"> </div>
</body>
</html>

------------------------------------------------------ Ajax code with comment

window.onload = initAll; //onload call the function "initAll"
var xhr = false; //global variable.
var xPos, yPos; //global variables for X and Y position.


function initAll() {
var allLinks = document.getElementsByTagName("a");

for (var i=0; i< allLinks.length; i++) {
allLinks[i].onmouseover = showPreview; //OnMouseOver call the function "showPreview"

}
}


//This "showPreview" function called based on event.
//The event is automatically passed to function as argument
//So no need to specify argument "evt" in the function call

function showPreview(evt) {
if (evt) {
var url = evt.target; //here target is the url or href of the article
}
else {
evt = window.event; //if event not passed automatically
var url = evt.srcElement;//Source element ie, url of the article
}
xPos = evt.clientX; //X cordinate from where event occure.
yPos = evt.clientY; //Y cordinate from where event occure.

////**** Actual AJAX Request code Start here ****////

if (window.XMLHttpRequest) {
//means if the browser have 'window.XMLHttpRequest',then create a XMLHttpRequest object 'xhr'.
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
//Internet Explorer methode to create a XMLHttpRequest object 'xhr'.
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}

if (xhr) {
//If XMLHttpRequest object 'xhr' successfully created
xhr.onreadystatechange = showContents; //OnReadyStateChange call the function "showContents" to handle the response coming back from the server.
xhr.open("GET", url, true); //Opening a request to send to server
xhr.send(null); //To send that opened request to server
}
else {
alert("Sorry, but I couldn't create an XMLHttpRequest");
}
return false;

////**** AJAX Request code End here ****////
}



function showContents() {

////**** Actual AJAX Response code Start here ****////

if (xhr.readyState == 4) {

if (xhr.status == 200) { //If request status is OK.if not working change "200" to "0" and try again.

var outMsg = xhr.responseText; //Text version of XMLHttpRequest
}
else {
var outMsg = "There was a problem with the request " + xhr.status;
}

var prevWin = document.getElementById("previewWin");
prevWin.innerHTML = outMsg;
prevWin.style.top = parseInt(yPos)+2 + "px"; // Convert to integer and add "px" to end,example 25px.
prevWin.style.left = parseInt(xPos)+2 + "px";
prevWin.style.visibility = "visible";
prevWin.onmouseout = function() {
document.getElementById("previewWin").style.visibility = "hidden";
}
}

////**** Actual AJAX Response code End here ****////
}

------------------------------------------------------ Ajax code without comment -- script.js

window.onload = initAll;
var xhr = false;
var xPos, yPos;

function initAll() {
var allLinks = document.getElementsByTagName("a");

for (var i=0; i< allLinks.length; i++) {
allLinks[i].onmouseover = showPreview;
}
}

function showPreview(evt) {
if (evt) {
var url = evt.target;
}
else {
evt = window.event;
var url = evt.srcElement;
}
xPos = evt.clientX;
yPos = evt.clientY;

if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}

if (xhr) {
xhr.onreadystatechange = showContents;
xhr.open("GET", url, true);
xhr.send(null);
}
else {
alert("Sorry, but I couldn't create an XMLHttpRequest");
}
return false;
}

function showContents() {

if (xhr.readyState == 4) {

if (xhr.status == 200) {

var outMsg = xhr.responseText;
}
else {
var outMsg = "There was a problem with the request " + xhr.status;
}

var prevWin = document.getElementById("previewWin");
prevWin.innerHTML = outMsg;
prevWin.style.top = parseInt(yPos)+2 + "px";
prevWin.style.left = parseInt(xPos)+2 + "px";
prevWin.style.visibility = "visible";
prevWin.onmouseout = function() {
document.getElementById("previewWin").style.visibility = "hidden";
}
}
}

------------------------------------------------------ CSS code

li a {
text-decoration: none;
font-weight: bold;
}

li a:hover {
text-decoration: underline;
}

h2, ul {
font-family: Georgia, "Times New Roman", Times, serif;
}

li {
list-style-type: none;
}

#previewWin {
background-color: #FF9;
width: 150px;
height: 200px;
font: .6em arial, helvetica, sans-serif;
padding: 5px;
position: absolute;
visibility: hidden;
border: 1px #CC0 solid;
overflow: hidden;
}

#previewWin h1, #previewWin h2 {
font-size: 1.0em;
}

------------------------------------------------------
************************************************* (C)
C
*************************************************
AJAX "Request" and "Response" Code
------------------------------------------------------AJAX Request Code
/*
Code snippet to create a new Ajax request
This code needs to be dropped into a function

Requires:
- Variable xhr to be declared globally
- A function called showContents to handle the completed request
(Or modify onreadystate assignment to use the correct function)
- The variable url needs to be set prior to this code
*/

if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}

if (xhr) {
xhr.onreadystatechange = showContents;
xhr.open("GET", url, true);
xhr.send(null);
}
else {
alert("Sorry, but I couldn't create an XMLHttpRequest");
}

------------------------------------------------------AJAX Response Code

/*
Code snippet to handle a completed Ajax response
This code needs to be dropped into a function
*/

if (xhr.readyState == 4) {
if (xhr.status == 200) {
var outMsg = xhr.responseText;
}
else {
var outMsg = "There was a problem with the request " + xhr.status;
}

// Do something here with outMsg
}

------------------------------------------------------
*************************************************(D)
D
*************************************************AJAX Example 2
AJAX Example - Goggle suggest - Using XML file

------------------------------------------------------ Html code

<html>
<head>
<title>Auto-fill states</title>
<link rel="stylesheet" rev="stylesheet" href="script.css" />
<script src="script.js" type="text/javascript">
</script>
</head>
<body>
<form action="#">
Please enter your state:<br />
<input type="text" id="searchField" autocomplete="off" /><br />
<div id="popups"> </div>
</form>
</body>
</html>

------------------------------------------------------ CSS code

body, #searchField {
font: 1.2em arial, helvetica, sans-serif;
}

#popups {
position: absolute;
}

#searchField.error {
background-color: #FC0;
}

div.suggestions {
background-color: #FFF;
padding: 2px 6px;
border: 1px solid #000;
}

div.suggestions:hover {
background-color: #69F;
}

------------------------------------------------------ Ajax code -- script.js

window.onload = initAll;
var xhr = false;
var statesArray = new Array();

function initAll() {
document.getElementById("searchField").onkeyup = searchSuggest;

if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}

if (xhr) {
xhr.onreadystatechange = setStatesArray;
xhr.open("GET", "us-states.xml", true);
xhr.send(null);
}
else {
alert("Sorry, but I couldn't create an XMLHttpRequest");
}
}

function setStatesArray() {
if (xhr.readyState == 4) {

if (xhr.status == 200) {
if (xhr.responseXML) {
var allStates = xhr.responseXML.getElementsByTagName("item");
for (var i=0; i<allStates.length; i++) {
statesArray[i] = allStates[i].getElementsByTagName("label")[0].firstChild;
}
}
}
else {
alert("There was a problem with the request " + xhr.status);
}
}
}

function searchSuggest() {
var str = document.getElementById("searchField").value;
document.getElementById("searchField").className = "";
if (str != "") {
document.getElementById("popups").innerHTML = "";

for (var i=0; i<statesArray.length; i++) {
var thisState = statesArray[i].nodeValue;

if (thisState.toLowerCase().indexOf(str.toLowerCase()) == 0) {
var tempDiv = document.createElement("div");
tempDiv.innerHTML = thisState;
tempDiv.onclick = makeChoice;
tempDiv.className = "suggestions";
document.getElementById("popups").appendChild(tempDiv);
}
}
var foundCt = document.getElementById("popups").childNodes.length;
if (foundCt == 0) {
document.getElementById("searchField").className = "error";
}
if (foundCt == 1) {
document.getElementById("searchField").value = document.getElementById("popups").firstChild.innerHTML;
document.getElementById("popups").innerHTML = "";
}
}
}

function makeChoice(evt) {
var thisDiv = (evt) ? evt.target : window.event.srcElement;
document.getElementById("searchField").value = thisDiv.innerHTML;
document.getElementById("popups").innerHTML = "";
}

------------------------------------------------------ Xml code

<?xml version="1.0"?>
<choices xml:lang="EN">
<item>
<label>Alabama</label>
<value>AL</value>
</item>
<item>
<label>Alaska</label>
<value>AK</value>
</item>
<item>
<label>Arizona</label>
<value>AZ</value>
</item>
<item>
<label>Arkansas</label>
<value>AR</value>
</item>
<item>
<label>California</label>
<value>CA</value>
</item>
<item>
<label>Colorado</label>
<value>CO</value>
</item>
<item>
<label>Connecticut</label>
<value>CT</value>
</item>
<item>
<label>Delaware</label>
<value>DE</value>
</item>
<item>
<label>Florida</label>
<value>FL</value>
</item>

</choices>

------------------------------------------------------
************************************************* (E)
E
*************************************************
"ResponseXML" and "ResponseText" response types.
----------------------------------------------------------------------------
"ResponseText" is the 'text' that the web server passes back in response from the server.
"ResponseText" --> Return response in Text fomat.

"ResponseXML" is the "object" "XMLDocument" that the webserver passes back in response from the server.
"ResponseXML" return response in XMLDocument Object format.

// xhr.responseText return requested 'colors.xml' file in Text format.
// xhr.responseXML return requested 'colors.xml' file in XMLDocument Object format.

If we using "ResponseText" response type, then we can easily access the elements or tags in the requested 'colors.xml' xml file using JavaScript functions 'getElementById' and 'getElementByTagName' etc--.And we can see elements using DOM inspector.

If we using "ResponseXML" response type, then we can also access the elements or tags in the requested 'colors.xml' xml file using JavaScript functions 'getElementById' and 'getElementByTagName' etc--.And we can not see elements using DOM inspector, because reponse is an XMLDocument object.

* Here client requesting an XML file in the server using JavaScript. Then the server send the requested XML file to JavaScript as response. Then the JavaScript accept the response in "ResponseXML" and "ResponseText" response format.

* Or can use "JSON" instead of "ResponseXML" and "ResponseText".

* There are number of choices to send Response back to JavaScript Code.
1) Most common choice currently is JSON which involves sending the data in the format of JavaScript code and JavaScript is grate to deal JavaScript.
2) We can send Response in plane text format (ResponseText) and JavaScript red that plane text and update the page based on it.
3) Another choice is XML. That is sending Response to JavaScript in XML format (ResponseXML).

------------------------------------------------------ Html code

<html>
<head>
<title>A Simple Ajax Script</title>
<script src="script.js" type="text/javascript">
</script>
</head>
<body>
<p><a id="requestXML" href="#">Request an XML file as XML</a></p>
<p><a id="requestText" href="#">Request an XML file as text</a></p>
<div id="updateArea"> </div>
</body>
</html>

------------------------------------------------------ ajax code -- with comment -- script.js

window.onload = initAll; //onload call the function "initAll"
var xhr = false; //global variable
var textRequest; //global variable

function initAll() {
document.getElementById("requestText").onclick = function() {
//anonymous function - function have no name
textRequest = true;
makeRequest(); //calling the function "makeRequest"
return false;
}
document.getElementById("requestXML").onclick = function() {
//anonymous function - function have no name
textRequest = false;
makeRequest(); //calling the function "makeRequest"
return false;
}
}

function makeRequest() {
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}

if (xhr) {
//onreadystatechange calling function "showContents" to handle server response
xhr.onreadystatechange = showContents;
//Means JavaScript send the request to server that please give me the file called 'colors.xml'.
//Server sends the 'colors.xml' xml file back as "ResponseXML" or "ResponseText" response format.
xhr.open("GET", "colors.xml", true);
xhr.send(null);
}
else {
document.getElementById("updateArea").innerHTML = "Sorry, but I couldn't create an XMLHttpRequest";
}
}

function showContents() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//responses xhr.responseText and xhr.responseXML
// xhr.responseText return 'colors.xml' file in Text format.
// xhr.responseXML return 'colors.xml' file in XMLDocument Object format.

var outMsg = (textRequest) ? xhr.responseText : xhr.responseXML;
}
else {
var outMsg = "There was a problem with the request " + xhr.status;
}
document.getElementById("updateArea").innerHTML = outMsg;
}
}

--------------------------- Ajax code -- without comment -- script.js

window.onload = initAll;
var xhr = false;
var textRequest;

function initAll() {
document.getElementById("requestText").onclick = function() {
textRequest = true;
makeRequest();
return false;
}
document.getElementById("requestXML").onclick = function() {
textRequest = false;
makeRequest();
return false;
}
}

function makeRequest() {
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}

if (xhr) {
xhr.onreadystatechange = showContents;
xhr.open("GET", "colors.xml", true);
xhr.send(null);
}
else {
document.getElementById("updateArea").innerHTML = "Sorry, but I couldn't create an XMLHttpRequest";
}
}

function showContents() {
if (xhr.readyState == 4) {
if (xhr.status == 0) {
var outMsg = (textRequest) ? xhr.responseText : xhr.responseXML;
}
else {
var outMsg = "There was a problem with the request " + xhr.status;
}
document.getElementById("updateArea").innerHTML = outMsg;
}
}

------------------------------------------------------ XML code

<?xml version="1.0"?>
<colors xml:lang="EN">
<color>
<name>Aqua</name>
<value>#00FFFF</value>
</color>
<color>
<name>Azure</name>
<value>#F0FFFF</value>
</color>
<color>
<name>Black</name>
<value>#000000</value>
</color>
<color>
<name>Blue</name>
<value>#0000FF</value>
</color>
<color>
<name>Brown</name>
<value>#A52A2A</value>
</color>
<color>
<name>Crimson</name>
<value>#DC143C</value>
</color>
<color>
<name>Cyan</name>
<value>#00FFFF</value>
</color>
<color>
<name>Gold</name>
<value>#FFD700</value>
</color>

</colors>

------------------------------------------------------
*************************************************

Ajax Note-1

AJAX Note-1
*****************************************************
XML Http Request ----> Essence of AJAX

AJAX --> Asynchronous JavaScript and Xml

Asynchronous means your browser doesn't hang while making request to server.

*****************************************************
Tools Required
----------------------
Text Editor ---> Eclipse, Komodo
Browser --->Firefox
Web Server ---> Apache

You Should Know HTML, CSS and JavaScript to study AJAX.

*****************************************************
Customizing Firefox for AJAX Development
--------------------------------------------------------------
3 Essential Add-ons used for AJAX Development are

1) DOM Inspector
2) Firebug
3) Web Developer ----> Important features is "View generated Source code" and "Outline block level elements".

*****************************************************
Document Object Model (DOM)
-----------------------------------
* DOM is an important part of JavaScript and AJAX.
* Keep in mind that every thing in the browser window (Document) is an object.
* Object on a webpage (Document) is called DOM.
* Examples of objects in a webpage are table, title, h1 etc and page itself is an object called Document object.
* Objects have properties.
* Table, title, h1 etc are properties (nodes) of Document Object.
* Row is a property of table Object
* Cell or column is a property of row Object

*****************************************************
XML
-------
A way of showing data in a text format taht parsable by scripting languages.
-------------------------------------
* Here we not only talk about objects (things) in the web page but also thing in any kind of document. XML is a kind of document.
* A browser can parse and understand XML.
* A Scripting language (JavaScript) can parse and understand XML.
* So we can parse and look an XML file in browser.
* So we can parse and look an XML file in JavaScript. <---- Use DOM inspector to check it.
* So we can parse and look an XML elements or tags in JavaScript as JavaScript object. <---- Use DOM inspector to check it.
* So we can access value from XML elements or tags in JavaScript as JavaScript object. <---- Use DOM inspector to check it.
-------------------------------------
We can do the same things with XML and JavaScript that are doing with webpage (html) and JavaScript.
For example, we can get element by id.
-------------------------------------
* XML using object model, so we can use XML tags and ids to retrieve information from XML files.
* Because of this browser and Ajax using XML as a way of getting data.
* We can use JavaScript to retrieve information from XML file using XML tags and ids.
-------------------------------------

*****************************************************
XMLHTTPRequest
-----------------------------
It is the core functionality of AJAX.
-----------------------------
* XMLHttpRequest is a JavaScript object. Every object has some properties.
* So XMLHttpRequest Object has some properties and methods.
* XMLHttpRequest Object properties have several different statuses (default predefined values).

-----------------------------
*****************************************************

Saturday, November 7, 2009

How to configure Relinace Netconnect in Debian Ubuntu Fedora Linux

First load the driver.

modprobe usbserial vendor=0x0eab product=0x9357

Modprobe in Ubuntu 9.04 stock installation may not work, in that case
add "usbserial.vendor=0x0eab usbserial.product=0x9357" to the end of
grub
listing without quotes.

Now edit the /etc/wvdial.conf file

Type Alt+F2 type "gksu gedit /etc/wvdial.conf" without quotes and
paste the below into it.

[Dialer Defaults]
#Reliance LXU 800
Init1 = ATZ
Init2 = ATQ0 V1 E1 S0=0 &C1 &D2 +FCLASS=0
Password =
Initz = ATQ0 M1 L1 X3 V1 E1 S0= 0 &C1 &D2 +FCLASS=0
Phone = #777
Model Type = USB Modem
stupid mode = 1
baud = 460800
New PPPD = yes
Modem = /dev/ttyUSB0
ISDN = 0
Username =
Abort on no dial tone = False

Save and close the file.

replace and with yours. Username and password must be
same and must be a number.

Now take terminal and do
wvdial
It should work.

Now after a restart you will notice that you will have to do modprobe again
if it was not added into the grub listing.

Edit /etc/modules file
Press Alt+F2 and type "gksu gedit /etc/modules" without quotes.

and append the below to the file and save and close.
options usbserial vendor=0x0eab product=0x9357

So any time you want to connect just do
wvdial
from terminal