Showing posts with label prototype. Show all posts
Showing posts with label prototype. Show all posts

Sunday, December 14, 2008

Thursday, December 4, 2008

AjaxContent

AjaxContent Class
The 2nd island of Ajax Islands is released. Using this class you can add Ajax links to your HTML pages without getting involved with JavaScript and XMLHttpRequest. You can associate a link (An A tag or any kind of HTML element as a link), a container (A DIV tag or any other container element) and URL(In fact, from the same server). So when the user clicks the link, the content of the URL will appear in the container. You can also introduce an image as a loading indicator to be displayed at the center (horizontally and vertically) of the container, so the user can wait for the new content to be fetched.

Download AjaxContent and take a look at live examples

The class has a very nice and powerful feature:
The last argument of the constructor, which is supposed to be a Boolean value, determines that if the script tags in the content should be added to the document scripts or not!!! (Not using a simple eval). So if you pass a true value to this argument, all script tag from the content will load and can be accessed from the current scripts of the page. 

Sunday, November 16, 2008

JavaScript Object Model - OO Programming


JavaScript is a C++-like scripting language and like most of its relatives let the programmers to write in both object oriented and procedural style. But there is a big difference between JavaScript and other popular OO languages such as C++ and Java which are class based languages.
OO languages are either class based or prototype based. JavaScript is one of prototype based languages out there.
There are lots of references and tutorials about OO programming in JavaScript in the Net. Most of them are so useful and explain a single aspect of OO programming in the language. Some are based on a particular framework such as Prototype, JQuery ... while some explain the pure JavaScript rules.If you are curious to read yet another nice article about JavaScript Object Model, I strongly suggest you to spend 15 minutes to read JavaScript's class-less objects by Stoyan Stefanov.
The article explains the dynamic features of the JavaScript and explains different ways to implement inheritance in the language and then compare them with Java's way.

Wednesday, November 5, 2008

Trick in AjaxForm

There is a small problem in using AjaxForm or any other Ajax tools, that is the visitor may cause JavaScript errors to be displayed if he/she triggers a function call before the JavaScript libraries or tools loads completely (Of course only if you try to load the JavaScript files dynamically!).
In the case of AjaxForm, it is possible that the user click submit button while the AjaxForm or Prototype is not loaded.
Solution is to prevent the user to submit the form before the libraries (JS files are loaded). So you must hide the submit button by setting its CSS attribute visibility to hidden. The AjaxForm object will make it visible automatically as soon as it is created.
So you should write the form this way:


<form id="form1">
username:
<input type="text" id="username" name="username" />
<br />
password:
<input type="password" id="password" name="password" />
<br />
<input style="visibility: hidden" type="submit" value="send" />
<input type="reset" value="reset" />
</form>

Monday, November 3, 2008

AjaxForm methods

Method

Description

submit()

You can submit the form by calling this function, but it is not necessary to use it usually, for example you can set the last field onBlure event to a function which calls this method.

reset()

You can reset the form and clear the message board by calling this method, but it is not necessary usually and it is called from other methods of the class.

resetForm()

You can reset the form but not clear the message board by calling this method.

hideForm()

This method will hide the form element (form tag). You may call this function when the server script has processed the data and the process was successful and user won't need the form anymore, similar to the login forms after successful login.

showMessage(msg, color)

This method let you show a message to the user such as data validation messages. The firs parameter is the message itself which is string and the second one is the color of message which is string too and could contain a color name e.g. "red" or a color value e.g. "#FF0000"

focusForm()

By calling this method the first input of the form will receive the focus. You may call this method after creating the object in order to make form ready to receive user's data.

Saturday, November 1, 2008

AjaxForm

After a long break in the development process of those Ajax components I promised to release here, I eventually, convinced myself to put the latest but still incomplete version of AjaxForm (the first component I decided to design and develop) here. I hope you enjoy its design and ease of use, that let you ajaxify a form by creating an object and calling some methods of that object from both client side scripts and the script which is coming from the server side result.
e.g.

var ajaxForm = new AjaxForm("frmEditUser", "edituser.act.php", "loader1.gif", "editBoard");
ajaxForm.focusForm();

But don't forget that all of these components which I'm working on are based on Prototype.js framework.

So in all examples I assume that you have the following line in your document's head section.


<script type="text/javascript" src="prototype.js"></script>

You can download the current version of AjaxForm here.

The design is based on the idea that each form has 4 main elements to be working as an web 2.0 form. (it is my idea, you may disagree with that)
  1. The form itself - HTML element (tag) of form, so we need to pass the ID of the form element to the AjaxForm object.
  2. The server side script which the forms's data will be sent to, so we pass the URL of the script to the object.
  3. The image that should be displayed as a loading animation while the user is waiting to receive the server result. We need to pass the URL of the image file to the AjaxForm object.
  4. The exact portion of the page that the animation image should be displayed, and also the place that other potential messages to the users should be displayed. So we pass the ID of an HTML element to the object.
The 4th factor could be divided to 2 separated factors, one HTML element for the animation image and one for the user messages, but I decided to have one for both, in order to keep the concept simple. I may add the feature in the final version. Anyway, according to these 4 factors, we can create an object of AjaxForm class like the following codes.

Example1

First add the followings to the head section of your page:

<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript" src="ajaxform.js"></script>


The HTML form.

<form id="form1">
username:
<input type="text" id="username" name="username" />
<br />
password:
<input type="password" id="password" name="password" />
<br />
<input type="submit" value="send" />
<input type="reset" value="reset" />
</form>


The place-holder for messages and the animation image.

<div id="board"></div>


Main part (instantiating the object)

<script type="text/javascript">
<!--
var ajaxForm = new AjaxForm("form1", "action1.php", "loader1.gif", "board");
ajaxForm.focusForm();
//-->
</script>

Don't forget to locate the following files in the same directory as your page directory:
  • prototype.js - you can download it here.
  • ajaxform.js - download it here.
  • loader1.gif - any gif animation
  • action1.php - a php file that will handle the request data

Now it's time to write the server side code. The server side script could be developed in any technology such as Java servlet, JSP, PHP, PERL, Python, ASP, ASP .NET and ...
In this example I write it using PHP (action1.php).

action1.php

<?php
$username = $_POST['username'];
$password = $_POST['password'];

$login = false;

if (empty($username)) {
$message = "You should enter your username!";
$color = "red";
} else if (empty($password)) {
$message = "You should enter your password!";
$color = "#FF7000";
} else if($username == 'ehsun' && $password == '7') {
$login = true;
$message = "You have logged in successfully.";
$color = "#335599";
} else {
$message = "Your username or password is incorrect!";
$color = "#9F9000";
}

echo "<script>";
echo "ajaxForm.showMessage('$message', '$color');";

if ($login) {
echo "ajaxForm.hideForm();";
} else {
echo "ajaxForm.focusForm();";
}

echo "</script>";

sleep(3);
?>


The sleep command is for simulating the delay! you don't need it in the real codes.

As you may noticed you have access to the AjaxForm object which has been created in the client side from the JavaScript code which is coming from server side script, that is very useful feature!
The AjaxForm has some other methods that I will explain in the next posts. Please give me your suggestions.

Wednesday, April 30, 2008

AjaxForm

Having my new web project started, I'm thinking about an agile solution for posting forms in an Ajax way with minimized JavaScript code.
Using prototype, my former solution was a functional approach...but now I'm thinking for a better OO approach.
Let see what can I do! I will put my solution here in next days.

Saturday, December 22, 2007

Google Suggest Tutorial

In the web sites and web applications most of the users are not aware of the exact and complete name of terms they are searching for! So it is a good idea to give them suggestion while they are trying to write the name of the desired words. Similar to what is happening in Google suggest.

In this tutorial we will do the same thing for a search in a group of people whose information are stored in a table of database. The same as the previous tutorials we use prototype.js as Ajax/DOM framework.

Since the steps are too simple and so similar to the previous tutorials, I let you download it and check it out by yourself! ;)

Good Luck!

Tuesday, December 18, 2007

Prototype and Scriptaculous Ebook


The first book about prototype.js framework and scriptaculous animation library!
Download the book here!

Tuesday, December 11, 2007

Ajax Chat - Using Prototype & PHP

In the past years chat rooms were so rare in the websites and only those website which needed it were using chat facilities. Most of those chat rooms were developed by means of Java Applet technology hence the client browser had to be Java-enabled in order to use the chat rooms. After a while flash chat rooms came in the picture but they had the same drawback since the client needs to have the Flash player plugin installed in order to use the chat rooms.
Recently the Ajax-enabled chat rooms have come to the websites even the personal websites. They are so light, easy to develop and don't need any special software or prerequisites on the clients' browsers.

In this tutorial we will learn how to develop a very simple Ajax-enabled chat room based on PHP 5 server-side scripting language and Prototype JavaScript framework.

You can develop this chat room following the steps bellow or download it here.

1. JavaScript Message class and one utility function
Create 2 folders called php and js. Copy the prototype.js file in the js folder.
Create a new javascript file called chat.js which contains the following code and put it in the js folder.

var Message = Class.create();
Message.prototype = {
initialize: function(id, timestamp, serverTimestamp, nickname, text) {
this.id = id;
this.timestamp = timestamp;
this.serverTimestamp = serverTimestamp;
this.nickname = nickname;
this.text = text;
},
};


function removeChildrenOf(s) {
while (s.hasChildNodes())
s.removeChild(s.childNodes[0]);
}


2. PHP Message class
Create a new php file called message.class.php which contains the following code and put it in the php folder.


<?php
class Message {

const MAX_TEXT_LENGTH = 100;
const MAX_NICKNAME_LENGTH = 20;

// ...........................................

private $id;
private $timestamp;
private $serverTimestamp;
private $nickname;
private $text;

// ...........................................

public function __construct($id = 0, $timestamp = 0, $serverTimestamp, $nickname = "", $text = "") {
$this->id = $id;
$this->timestamp = $timestamp;
$this->serverTimestamp = $serverTimestamp;
$this->nickname = $nickname;
$this->text = $text;
}

// ...........................................

public function setId($id) {
$this->id = $id;
}

public function getId() {
return $this->id;
}

public function setTimestamp($timestamp) {
$this->timestamp = $timestamp;
}

public function getTimestamp() {
return $this->timestamp;
}

public function setServerTimestamp($serverTimestamp) {
$this->serverTimestamp= $serverTimestamp;
}

public function getServerTimestamp() {
return $this->serverTimestamp;
}

public function setText($text) {
if(strlen($text) > self::MAX_TEXT_LENGTH)
echo "Error: Text is too long! Maximum is ".self::MAX_TEXT_LENGTH;
else
$this->text = $text;
}

public function getText() {
return $this->text;
}

public function setNickname($nickname) {
if(strlen($text) > self::MAX_NICKNAME_LENGTH)
echo "Error: Nickname is too long! Maximum is ".self::MAX_NICKNAME_LENGTH;
else
$this->nickname = $nickname;
}

public function getNickname() {
return $this->nickname;
}
}
?>


3. Database, Tables and Configuration
Create a database in your mysql DBMS and run the following query on it in order to create the message table.


CREATE TABLE `message` (
`id` int(10) unsigned NOT NULL auto_increment,
`timestamp` bigint(20) unsigned default NULL,
`text` varchar(100) default NULL,
`serverTimestamp` bigint(20) unsigned default NULL,
`nickname` varchar(20) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;


Create a php file called config.inc.php which contains the following code and put it in the php folder.
Don't forget to write database name, username and password of your mySql server instead of corresponding parameters in this file.

<?php
define("DB_HOST", "localhost");
define("DB_USERNAME", "root");
define("DB_PASSWORD", "ebic");
define("DB_NAME", "chat");
?>


4. Send Message server-side script

Create a php file called send.php which contains the following code, don't put it in any folder, let it be in the root folder of your website.


<?php
include_once('./php/config.inc.php');

$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$text = isset($_POST['text']) ? $_POST['text'] : "";
$timestamp = isset($_POST['timestamp']) ? $_POST['timestamp'] : 0;
$serverTimestamp = isset($_POST['serverTimestamp']) ? $_POST['serverTimestamp'] : 0;
$nickname = isset($_POST['nickname']) ? $_POST['nickname'] : "";

$sql = "INSERT INTO message (text, nickname, timestamp, serverTimestamp)
VALUES('$text', '$nickname', '$timestamp', '$serverTimestamp')";

if (!$mysqli->query($sql)) {
echo "Error in query";
}

?>


5. Receive Messages server-side script
Create a php file called get.php which contains the following code, don't put it in any folder, let it be in the root folder of your website.


<?php
include_once('./php/config.inc.php');

header('Content-type: text/xml');

$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

echo "<messages>";

$timestamp = time();
$sql = "DELETE FROM message WHERE $timestamp - serverTimestamp > 1000 ";

if (!$mysqli->query($sql)) {
echo "Error in query";
} else {
$sql = "SELECT * FROM message";
if (!$result = $mysqli->query($sql)) {
echo "Error in query";
} else {
while($record = $result->fetch_assoc()) {
echo "<message>";

echo "<id>";
echo $record['id'];
echo "</id>";

echo "<timestamp>";
echo $record['timestamp'];
echo "</timestamp>";

echo "<serverTimestamp>";
echo $record['serverTimestamp'];
echo "</serverTimestamp>";

echo "<text>";
echo $record['text'];
echo "</text>";

echo "<nickname>";
echo $record['nickname'];
echo "</nickname>";

echo "</message>";
}
}
}

echo"</messages>";

?>


6. Utility server-side script for getting the server timestamp
Create a php file called timestamp.php which contains the following code, don't put it in any folder, let it be in the root folder of your website.


<?php
echo mktime();
?>


7. Client script for sending and getting (main html page)
Create a html file called index.html which contains the following code, don't put it in any folder, let it be in the root folder of your website.


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Chat Room (Shout Box)</title>
<script type="text/javascript" src="js/prototype.js"></script>
<script type="text/javascript" src="js/chat.js"></script>

<script type="text/javascript"><!--
<!--

var serverTimestamp = 0;
var messages = new Array(10000);
var msgCount = 0;

function existInArray(msg) {
for(i = 0; i < msgCount; i++) {
if(msg.timestamp == messages[i].timestamp)
if(msg.serverTimestamp == messages[i].serverTimestamp)
return true;
}
return false;
}

function getMessages() {
new Ajax.Request('get.php?ts=' + new Date().getTime(), {
onSuccess: function(transport) {
var xml = transport.responseXML;
var msgNodes = xml.documentElement.childNodes;
for(i = 0; i < msgNodes.length; i++) {
var id = msgNodes[i].getElementsByTagName("id")[0].firstChild.nodeValue;
var nickname = msgNodes[i].getElementsByTagName("nickname")[0].firstChild.nodeValue;
var text = msgNodes[i].getElementsByTagName("text")[0].firstChild.nodeValue;
var timestamp = msgNodes[i].getElementsByTagName("timestamp")[0].firstChild.nodeValue;
var serverTimestamp = msgNodes[i].getElementsByTagName("serverTimestamp")[0].firstChild.nodeValue;
var msg = new Message(id, timestamp, serverTimestamp, nickname, text);
//alert(i);
if(!existInArray(msg)) {
messages[msgCount++] = msg;
}
}
}
});

showMessages();
setTimeout("getMessages()", 4000);
}

function updateServerTimestamp() {
new Ajax.Request('timestamp.php?ts=' + new Date().getTime(), {
onSuccess: function(transport) {
serverTimestamp = transport.responseText;
}
});
}

function showMessages() {
var board = $('board');
removeChildrenOf(board);
for(i = 0; i < msgCount; i++) {
var msgView = document.createElement("div");
var msg = messages[i];
var date = new Date(parseInt(msg.timestamp, 10));
msgView.innerHTML = msg.nickname + " <small>(" + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + ")</small>: " + msg.text;
board.appendChild(msgView);
}
board.scrollTop = board.scrollHeight;
}

function sendMessage(msg) {
new Ajax.Request('send.php', {
method: 'post',
parameters: {
text: msg.text,
nickname: msg.nickname,
timestamp: msg.timestamp,
serverTimestamp: msg.serverTimestamp
},
onFailure: function() {
sendMessage(msg);
}
});

}

function doMessage() {
if ($F("message").length > 0) {
var board = $('board');
var msg = new Message(0, new Date().getTime(), serverTimestamp, $F('name'), $F("message"));
//alert(msg.timestamp);
messages[msgCount++] = msg;
showMessages();
sendMessage(msg);
board.scrollTop = board.scrollHeight;
}
$('message').clear();
$('message').focus();
updateServerTimestamp();
}

Event.observe(window, 'load', function() {
updateServerTimestamp();
getMessages();
});


//-->
</script>


<style>
<!--

#board {
width: 400px;
border: inset 2px;
height: 300px;
padding: 2px;
overflow: auto;
}

-->
</style>
</head>
<body>

<h1>Chat Room</h1>

<form action="" onsubmit="return false;">
<div id="board"></div>
<br />
<label>Nickname:</label>
<input type="text" name="name" id="name" maxlength="20" />
<br />
<label>Message:</label>
<input type="text" id="message" name="message" maxlength="100" size="45"/>
<input type="submit" value="Send" name="send" onclick="doMessage()"/>
</form>
<br />
<br />
<a href="http://ehsun7b.blogspot.com">ehsun7b.blogspot.com</a>
</body>
</html>



Enjoy chatting in your own website!

Saturday, October 27, 2007

Ajax clock, an alive clock using the server time

In this tutorial we will see how easy is to develop a simple clock using the prototype Ajax classes, specifically Ajax.PeriodicalUpdater class.

You can download this tutorial files here.

Developing a JavaScript clock is not so difficult, and there are a bunch of them available in the net. But sometimes we need to show the server's time on the clock, instead of using the clients' own machine time. So the solution is Ajax if we want to have an interactive (alive) clock on the page which is showing the server's time without refreshing the page again and again.


1.
Create a html file and write the following code :

in the head section:



in body section:




2.
Create a PHP file called clock.php containing the following code:




3.
Create a floder called js besides these files and copy the prototype.js in it. You can download the latest version of prototype framework here.

Thats it! Copy all the files in the apache htdocs folder and enjoy!


Explanation:

We have a div with id="clock" in the html body which is our placeholder for displaying the time.
In the JavaScript section we have created a new object of class Ajax.PeriodicalUpdater which is one of the Ajax classes provided by prototype framework.
According to the prototype document:

This object addresses the common need of periodical update, which is used by all sorts of “polling” mechanisms (e.g. in an online chatroom or an online mail client).

So we don't need to provide a mechanism for fetching the time again and again, this object will repeat its job automatically based on its frequency option in the options parameter.
The first parameter is the id of the HTML element which will show the result and the second one is the URL for the request (XMLHttpRequest).

Enjoy Ajax!