Prototype Javascript – Introduction


Click this image to view the official website of Protoype

- INTRODUCTION -

I am currently working on a huge web-based application project for our customer in the United States. It is a customer (client) – company (server) end to end solution that tends to ease their business transactions by making them online – in short accessible anywhere. We are using the MVC pattern but haven’t implemented any of the existing Java Frameworks. Subdivided into three layers, Front End-Business Delegate-DAO, the said application runs on Tomcat Server (Web) and JBoss Server (Application)

Focusing on the Front End (client views), we have used the AJAX technology to asynchronously connect our JSP’s to our Servlets and do the necessary end to end processing of data (both request and JSON objects).

Now the big question is – how does our JSP sends and receives data to and from the server? Is it possible that a simple JSP could dynamically execute AJAX calls, form data and event handling, and present the result in an expected format?

Apparently, the answer is a big YES! And this is because of the javascript framework that we are currently using. It is, without further ado, called “PROTOTYPE”.

This Javascript framework allows you to develop dynamic web applications with ease at it provides functions that are of great help to dynamic content pages. Such functions are the following:

- Document Object Model Manipulation
- Object Oriented Programming in Javascript
- Data Manipulation
- XML and JSON data format support
- AJAX calls with ease

All you have to do is to import the prototype.js file in your page/application and its functions are ready for your usage.

This series will guide you on how to use the Prototype Framework. Actual web application examples are also given in order for you to use them on the go. Most of its contents are taken from the Prototype guide as well as from the consolidated examples on the web and on my actual work.

- UTILITY METHODS (PART 1) –

These might be the most useful methods of Prototype framework. If Java has core syntax and commands, these are the Prototype counterpart. You might see yourself using these methods over and over again as it acquires, manipulates, and presents data in your web document dynamically.

Note: DOM knowledge is a prerequisite on this part as these methods are well used on Form elements manipulation.

————————————————————————
$
Syntax: $(id/element)  HTML Element

————————————————————————

The conventional DOM way of acquiring an element in a web document is through the document.getElementById() syntax. Apparently, Prototype simplifies it by just using the dollar ($) sign and the id of the expected element to manipulate. Thus, this statement will return the actual element for further manipulation.

DOM: document.getElementById(‘username’);

PROTOTYPE: $(‘username’);

After acquiring the element, you can do the manipulation:
1) Alerting the value of the textbox:

var tBox = $(‘username’);
alert (tBox.value);

2) Changing the class name of the textbox

var tBox = $(‘username’);
tBox.className = ‘myTextBox’;

————————————————————————
$$
Syntax: $(css Rule)  Array of HTML Elements

————————————————————————

This is a great way to acquire multiple elements based on a rule. A replacement on either document.getElementsByTagName() or document.getElementsByClassName(). It will return an array of HTML Elements which you can iterate for manipulation.

DOM: document.getElementsByTagName(‘input’);

PROTOTYPE: $$(‘input’);
After acquiring the element, you can do the manipulation:
1) Alerting the value of the textboxes:

var tBoxes = $$(‘input’);
tBoxes.each(function(e){
alert (e.value);
});

Note: The .each() function is the Prototype way to iterate objects. It is an alternative for looping statements.

Adding Libraries to a Dynamic Web Application in Eclipse

I am currently developing a simple web application that would apply the MVC architecture. To those new to the MVC term, it stands for Model-View-Controller. An architecture used for simple applications that separates the GUI pages (for end client), the business logic (reusable classes), and the controller (that controls the event or method call). You can easily implement this in Eclipse by creating a new Dynamic Web Application project.

Apparently, during the development process, I’ve encountered a simple yet very important problem. My Database related classes can’t locate the classes from Postgre (which is my database system). This is due to the Library from Postgre that my code is looking.

The big question now – “How will I add a library in my Dynamic Web Project?”

Well, in a simple Java Project, this is easy but for a project of this kind where your sources are placed in a separate directory scheme it is the other way around.

I found this thread and it worked:

http://dev.eclipse.org/newslists/news.eclipse.webtools/msg11326.html

The solution is quite straightforward:
- Right click on the your web project and choose PROPERTIES
- Choose the J2EE Module Dependencies
- Click on the Add External JARs… and then point on your library file (ZIP or JAR)
- Click on Apply then OK.
- Restart your Apache Tomcat

The added library should be seen under: ProjectName > Java Resources: src > Libraries > WebApp Libraries.

ARMAN

The Magic of PreparedStatement Interface

If you are working on a Java Project that requires data storage and manipulation, a Java interface could be of great help to you. The “PreparedStatement” interface, under “java.sql” package, pre compiles and stores your SQL statements in an object to efficiently execute the said statement multiple times. There are setter methods that you have to use in order to define the values needed in a statement. Let’s take this example:

PreparedStatement pstmt = con.prepareStatement(“UPDATE EMPLOYEES SET SALARY = ? WHERE ID = ?”);

The object “pstmt” stores the “UPDATE” query for further execution. Notice that the query has question marks (?) characters. The values here could be acquired from a variable or an explicit value that you set using the setter methods of the PreparedStatement Interface (i.e. pstmt.setDate(), pstmt.setObject(), pstmt.setString()). Going back to our example, here is a complete usage of the said interface:

PreparedStatement pstmt = con.prepareStatement(“UPDATE EMPLOYEES SET SALARY = ? WHERE ID = ?”);pstmt.setBigDecimal(1, 153833.00)
pstmt.setInt(2, 110592)

Upon execution, the sql query will execute an “UPDATE” query to “EMPLOYEES” table setting a “SALARY” of “153833.00” to a row with “ID” of “110592”. The first parameter of the given methods is the sequence of the question mark in the actual query statement. That is, the setBigDecimal with “1” parameter takes the question mark of “SALARY” and the setInt for “ID”.

This interface makes your query statements acquire values in a versatile way. Since we are dealing with multiple data in terms of data storage, this scheme would be of great help.

TIP: Check the Java Documentation for the required parameters of the setter methods. I had some difficulties when I initially used this in my code. Nonetheless, this is of great help. :D

Limiting Decimal Points in Java

Limiting the decimal points/places of a double/float value is very important mostly when you are dealing with average or amount. Usually, the JVM presents the maximum number of decimal places depending on the type used. Apparently, having more than three decimal points could be disturbing. Other languages like Turbo C/C++ deals with this by just simply adding the limit keywords (dot + number of decimal places + the charcter ‘F’) In Java, there are two ways to do it:

USING THE ‘setScale’ METHOD IN ‘BigDecimal’ CLASS Let us take this code snippet for instance:

double num = 4.00900990;
int decimalPlace = 2;
BigDecimal bd = new BigDecimal(num);
bd = bd.setScale(decimalPlace,BigDecimal.ROUND_UP);
System.out.println (bd);

In this code, the ‘num’ variable’s decimal value needs to be limited into 2 decimal places. To do this, the BigDecimal class under the java.math package should be used. After instantiating an object (‘bd’), you will now call the setScale method that accepts the ‘decimalPlace” which is 2 and the constant value BigDecimal.ROUND_UP for rounding up the values. The value with only 2 decimal places will then be printed in the console. This scheme in Java is quite complicated.

USING THE ‘System.out.format()’ METHOD

This apparently is the easiest way. The method takes two arguments: the output format and the string to display. Here’s an example that adds a dollar sign and commas to the display of an integer:

int accountBalance = 5005;
System.out.format(“Balance: $%,d%n”, accountBalance);

This code produces the following output:

Balance: $5,005

The formatting string begins with a percent sign (“%”) followed by one or more flags. The “%,d” code displays a decimal with commas dividing each three digits. The “%n” code displays a newline character. The next example displays the value of pi to 11 decimal places:

double pi = Math.PI;
System.out.format(“%.11f%n”, pi);

The output:
3.14159265359

Tweak Mouse Pointers using CSS

I updated the Multiply Site of my ex-high school computer organization when I realized that it would be better if the mouse pointer will be changed. Oh! The Cascading Style Sheet (CSS) is the best technique to change this. It has a rule that directly modifies the mouse pointer that a user sees.

How to add a CSS declaration in your HTML File
Adding a custom CSS in a web page could be done in different ways. But embedding such is the easier one (though not always recommended). Here is an example of an embedded CSS in a webpage:

<style type = “text/css>
rules…
</style>

Notice that by using the <STYLE> container tag, you can add a custom CSS. Inside the said tag are the rules needed for the page.

Now, here are some of the rules in modifying the page’s mouse pointer (hover on each rule inside a box to see the actual pointer):

{
cursor: auto;
}

{
cursor: crosshair;
}

{
cursor: default;
}

{
cursor: pointer;
}

{
cursor: move;
}

{
cursor: e-resize;
}

{
cursor: ne-resize;
}

{
cursor: nw-resize;
}

{
cursor: n-resize;
}

{
cursor: se-resize;
}

{
cursor: sw-resize;
}

{
cursor: s-resize;
}

{
cursor: w-resize;
}

{
cursor: text;
}

{
cursor: wait;
}

{
cursor: help;
}

By the way, you can embed the tag inside the or tags. Though most developers are using the former. These sample rules are taken from ShewShack site.

DATABASE QUERY TECHNIQUES



I am currently studying an open source Database Management System called “Postgre” Apparently; this is the required back-end of our applications as it runs with Java and using the UNIX platform. Its queries are quite straight and most of them conform to the SQL Query Standards. Though there are some additions that would return to a query error if you misused.

As I go along with the database’s documentation, I saw these two database techniques that could simply your life. These INSERT and CREATE techniques will change the conventional way of inserting and creating tables. Here it is:

INSERTING A WHOLE TABLE TO ANOTHER
To insert a whole table into another, you can also use INSERT. Both tables have to contain the same columns with the same name and datatype.

INSERT INTO products (SELECT product_no, name, price FROM products_old);

If the columns in both tables are in the same order you can also replace the column names by an asterisk:

INSERT INTO products (SELECT * FROM products_new);

This is very useful when you want to remerge a temporary modified table with the genuine table which was the base of the temporary one. Simply truncate the genuine table with TRUNCATE TABLE products; and than use the above INSERT statement.

CREATING TABLES FROM OTHER TABLES
The INTO TABLE clause may be used with any valid SELECT query in order to create a new table with the column structure and row data of the returned result set. The syntax for this is as follows:

SELECT select_targets
INTO [ TABLE ] new_table
FROM old_table;

This syntax performs an implicit CREATE TABLE command, creating a table with the same column names, value types, and row data as the result set from the original table. When the message SELECT is returned, you will know that the statement was successfully performed, and the new table created.

booktown=# SELECT * INTO stock_backup
booktown-# FROM stock;
SELECT

The table specified by the INTO clause must not exist, or else an error will be returned. Upon the error, the values of the query will not be inserted and the query will fail. Note that the TABLE keyword, in this query, is an optional noise term.

Using “SELECTINDEX” property in Java Scripts

A college friend of mine asked for support re his Web Development project. He is developing an online banking application using HTML with Java Scripts. His page will be able to add deposits and subtracts withdrawals from the user’s current balance. A form selection (in a form of <SELECT> tag) is used to choose whether the transaction is DEPOSIT or WITHDRAW.

His program should call a Java Script function that would either add or subtract depending on the chosen transaction. Apparently, this is his problem. I realized upon observing his code that the said SELECT tag is only calling one function that only does the same function – subtracting the amount entered to the one existing.

To solve this – the SELECTINDEX property should be used to determine which transaction the user has chosen. Here is a code snippet that I’ve created:

<script language = “JavaScript”>
function doMath()
{
if (document.myform.selection.selectedIndex == 0)
document.myform.text3.value = parseInt(document.myform.text1.value) + parseInt(document.myform.text2.value);
else
document.myform.text3.value = parseInt(document.myform.text1.value) – parseInt(document.myform.text2.value);
}
</script>

Notice that the doMath() function does the following tasks – check whether the option (with an index of 0) is selected. If it is true, the text3 value of the form will be taken from the sum of deposit and existing amount. If false, it will do the subtraction. Actually, the selectIndex property has an integer value that starts with zero (0).

He smiled when I sent this. Problem solved. :D

Take note:
You will notice from the given code snippet that the parseInt() method is used. This is for the purpose of converting the value of text1 and text2 to an integer from its original type of string.

The “Tiga Lipa Are” Virus


The Lipanians must be really proud.

I accessed MY COMPUTER and clicked on the Hard Disk C: icon. I noticed that the said link isn’t opening. Apparently, nothing happens. Then I tried the other partition still with no avail. When I tried the Removable Drive icon, it opened but in another window. I know there is a problem. Simple yet it would cause big harm in the future. So I opened the web browser to check the cause. To my surprise, the Title bar shows the web page title and “Tiga Lipa Are” words. Waaaaah! There really is something wrong. A Trojan Virus has infected my machine. Poor Norah!

Upon my research, I realized that this virus has been created by a student from Mapua. Your computer is infected if:

- The words “TAGA LIPA ARE” on your Internet Explorer title bar
- Inability to change your IE7 homepage
- Inability to double click to open any of your disc drives (this includes removables, but you can open them in Windows Explorer)
**Take note: This wouldn’t take in effect with Mozilla Firefox.

Apparently, Norah has these symptoms. Also take note that this virus is acquired through removable devices such as your USB. Here are some tips to eliminate the possibility of acquiring viruses through that drive:

- Always scan your USB drive before using. AVG, Norton, Kaspersky, and AntiVir are good anti-virus program for this.
- When the auto run program pops up, CANCEL it. Open your USB drive using the RUN program instead. This is because of the autorun.inf file installed inside your USB.
- Before opening your USB, show all hidden files by:
a. Clicking the TOOLS > FOLDER OPTIONS
b. Choose the VIEW tab
c. Under the HIDDEN FILES AND FOLDERS, choose Show Hidden Files and Folders
d. Uncheck the Hide Extensions for known file types and the Hide Protected Operating System Files
* These will enable you to see the hidden dangerous files and delete them manually. Though take note of the System Files that you might delete accidentally.

Luckily, there is a program developed to fight this virus. I have seen this through this blogsite Winning the fight against the “TAGA LIPA ARE Virus”

Just download the mini program there, run the executable file, and restart your machine. This program will delete the script that causes the problems and automatically change the settings of your registry (apparently, just deleting the instances of this virus)
Indeed, Pinoys are great virus developers. But we really have to take into consideration the danger this might bring. We might be famous because of this creation but will eternally be condemned due to the effect it will bring.

:D

“Hello World!” – The very first entry

The beginning of a source code depends on the programming language a developer is using.

import java.lang.*
import javax.swing.*

Java, for instance, usually imports java classes by using the IMPORT keyword

#include <stdio.h>
#include <conio.h>

Turbo C/C++ includes library files by using the INCLUDE keyword

<HTML> <HEAD>
Web pages normally start with an HTML container tag.

OPTION EXPLICIT
And Visual Basic could use the OPTION EXPLICIT statement to eliminate to prompt the program that all variables should have a data type.

As for me and for this technical blog, I just would like to start this with an opening statement of

“HELLO WORLD!”

I have conceived this site when my computer, Norah, was infected by a Trojan Virus called “Tiga Lipa Are” I saw a solution through a technical blog Google presented to me during my search. I was inspired and was able to learn that setting up my own site will be of big help. This will be a documentation effort for me and an additional resource for my visitors.

I do hope that this will be an avenue for learning, solutions, and fun as well. I will do my best to update this with the latest and accurate information.

Thanks for visiting my Technical Blog! Btw, what the hell is the reason why I used “Tuldok System” as the site’s title? Well, not just because of me being a TULDOK typist but this site will serve as technical notes in a (frustrated “Joke!”) developer’s point of view.

Enjoy!

  •  

    November 2009
    M T W T F S S
    « May    
     1
    2345678
    9101112131415
    16171819202122
    23242526272829
    30  
  • What I am currently reading?

  • “Tuldok System” has been featured by WordPress.com