Recent Comments
Updated Ajax tutorials - Most wanted on Internet
1.www.ajax-tutorials.com - Ajax Tutorial Top List - Free tutorials, articles, examples for web 2.0.Ajax Tutorial TopList. More than 400 free tutorials, articles and examples sorted by categories.
2.www.ajaxprojects.com - Ajax Projects - Asynchronous Javascript and XML.
3.www.ajaxtutorial.net - Ajax Tutorial : Ajax Help and Tutorials.
4.www.ajaxrain.com - 1125 + Ajax/Javascript/Dhtml examples and demos to download.With a diverse collection of over 900 Ajax examples, java scripts, jQuery plug-ins, DHTML codes and demos from around the web, Ajaxrain gives you the perfect start to web development.
5.www.ajaxdaddy.com - AjaxDaddy - Ajax Examples in Action.Ajax examples, javascript scripts and web 2.0 demos in action.
6.freeajaxscripts.net - Ajax Code Examples, Free Ajax Scripts, Ajax Downloads - Free Ajax Scripts
7.www.ajax.org - Ajax.org - Declarative Development and Rich UI's
8.www.ajaxmatters.com - AJAX Matters : Indepth AJAX Tutorials, Articles and More
9.adaptivepath.com - adaptive path » ajax: a new approach to web applications.A User Experience design and consulting firm that unites theory and practice to advance the art of user experience design while helping clients make better business decisions. Located in San Francisco, California, USA.
10.developer.mozilla.org - Getting Started - MDC
11.developer.mozilla.org - AJAX:Getting Started - MDC
12.asp.net - ajax - Microsoft portal site for the ASP.NET development community. Download Visual Web Developer, post to the forums, read ASP.net blogs and learn about ASP.net.
13.w3schools.com - ajax - Free HTML XHTML CSS JavaScript DHTML XML DOM XSL XSLT RSS AJAX ASP ADO PHP SQL tutorials, references, examples for web building.
.... they are most viewed ajax web sites on the internet. I hope you find them useful.
Creating an Ajax-driven Drop-down Menu System - 40
Creating a Shopping Cart - Buy item by dragging it to the shopping cart
Handling Multiple XMLHttpRequest Requests - Ajax Power - 32
Using Two XMLHttpRequest objects - Ajax tutorial - 31
Calling a Different Domain Safely - Getting Ajax Power - 30
Connecting to Google Suggest - Live Google Search - Ajax Training 29
Extracting Data From XML - ajaxtraining.blogspot.com - 22
Fetching XML Data From the Server - Ajax Training - 21
Storing Ajax Data in XML - Ajaxtraining.blogspot.com - 20
Selecting Relative or Absolute URLs - Ajax tutorial - 17
Decoding the Fetched Data - Ajax Tutorial - 16
Fetching Text Data From the Browser - Ajax training 15
Problems creating an XMLHttpRequest Object -Ajax tutorial 14
Checking the XMLHttpRequest Object's status property - 12
Singleton Pattern
I will show you how to take your
Objects that utilize the Singleton pattern provide a consistent reference for other objects in the web application. A Singleton object is one that cannot be instantiated more than once. This means that multiple instances of the object cannot be created. You might be asking why you would want an object that cannot be instantiated by other objects in a web application. we will explain why, help you understand how this pattern is useful, and show you how to use this pattern in your Ajax applications by creating an object that handles all of your Ajax updates.
An Overview of the Singleton Pattern
Imagine having a large-scale
Creating an Object Using the Singleton Pattern
Creating a JavaScript object with the Singleton pattern is so simple and intuitive. To instantiate a Singleton object, simply write the following line of code:
AjaxUpdater = {};
Instantiating the object is truly this simple and, as you can see, it only allows us to create the one reference to the object within the object itself. This object will then be used throughout the rest of the web application for constant reference. Now that we have our object instantiated, all we have to do is call it by name from anywhere in the application to access its properties and methods.
Creating properties and methods in a Singleton object is just as simple as instantiating the object. Write the name of the object, followed by the name of the method, and then point it to a new function, with any associated parameters if necessary. Take a look at the example of the initialize method in the below code snippet.
1.Creating a Method in a Singleton Object (AjaxUpdater.js
)AjaxUpdater.initialize = function()
{
AjaxUpdater.isUpdating = false;
}
AjaxUpdater.initialize();
The initialize method needs to be invoked after it is created in order to initialize the
object before we can use the rest of its methods. It also prevents JavaScript from throwing an error because the method will not have existed at this point.
This method initializes the AjaxUpdater and, although it does not accept any parameters, it is used to set all the
local properties for the object. If this object is not initialized, the properties of the object will not be properly instantiated when we try to
access their values, resulting in unexpected behaviors. Creating a property in a Singleton object is as simple as typing the name of the object, followed by
the property you want to create.
AjaxUpdater.isUpdating = false;
In the preceding example, we are creating a Boolean property named isUpdating. This property is set to false by default because the object is not currently active, which means that it is not currently updating any requests or waiting for any responses. The isUpdating Boolean will be used to determine whether the object is currently updating a request or waiting for a response from the
2.The Update Method in the AjaxUpdater (AjaxUpdater.js)
AjaxUpdater.Update = function(method , service, callback)
{
if(callback == undefined || callback == "")
{
callback = AjaxUpdater.onResponse;
}
Ajax.makeRequest(method, service, callback);
AjaxUpdater.isUpdating = true;
}
The first section of code in the Update method is an if statement, which checks for the callback parameter. We check to see if this value is undefined or an empty string. If it is, we set it to a default method named onResponse, which is a method that will exist in the AjaxUpdater object. When we are sure that we have a callback method set, we move on to make our XHR through the
The onResponse method that we use as a default callback method is very simple and can be used for any default response that you would like; see the below code snapshot, In the example, I am simply using it as a way to reset the isUpdating Boolean back to false, but you could use it to display a default, custom loading message, and so on.
3.The onResponse Method in the AjaxUpdater
(AjaxUpdater.js)AjaxUpdater.onResponse = function()
{
if(Ajax.checkReadyState('loading') == "OK"){AjaxUpdater.isUpdating = false;
}
}
If we do not use this default callback method, we will need another way to set the isUpdating Boolean to false. I have decided to set this variable directly in the
Ajax Patterns
Design patterns are extremely useful when developing large-scale applications. Design patterns provide code flexibility and help establish a way of handling common situations that occur in the logic of an application.
Ajax Patterns are mainly classified into six different design patterns
Singleton Pattern
A Singleton object is one that cannot be instantiated more than once. the Singleton pattern solves the problem of having to instantiate multiple instances of an object throughout an application by simply giving our application one reference that never changes. This is how the Singleton pattern specifically solves a common programming problem. Read more...
Model - View - Controller
The Model View Controller (MVC) pattern is the separation of an application's graphical user interface (GUI) from its core logic. Read more...
The Observer Pattern
The Observer pattern is a design pattern that is used to observe the state of an object in an application. The observed object allows other objects to register and unregister as observers. The observers are notified when specific events that they are observing are fired. Read more...
Data Reflection Pattern
The Data Reflection pattern is a pattern that keeps web application content in sync with the database and with the file it is requesting. Read more...
Interaction Patterns
There are many interaction patterns emerging in the budding presence of Ajax. Web applications can now have front-end functionality that is much more complex, such as interacting with the database without a browser refresh. Read more...
Usability Patterns
The usability patterns are designed to provide a more intuitive user experience and eliminate all the annoying JavaScript dialogs that have existed in many applications over the years. The GUI should be free of questions and uncertainty. Read more...
Buy a television by dragging it to the shopping cart | Ajax Drag and Drop
Buy a television by dragging it to the shopping cart
<html>
<head>
<title>Ajax Drag and Drop</title>
<style type="text/css">
#television {
position:absolute;
z-index:200;
background: #FF0000;
color:#0000FF;
}
#target {
position:absolute;
background: #00FF00;
color:#000000;
}
</style>
<script type="text/javascript">
var offsetX, offsetY;
function MouseEvent(e)
{
if(e) {
this.e = e;
} else {
this.e = window.event;
}
if(e.pageX) {
this.x = e.pageX;
} else {
this.x = e.clientX;
}
if(e.pageY) {
this.y = e.pageY;
} else {
this.y = e.clientY;
}
if(e.target) {
this.target = e.target;
} else {
this.target = e.srcElement;
}
}
function addListener(type, callback)
{
if (document.addEventListener) {
document.addEventListener(type, callback, false);
} else if (document.attachEvent) {
document.attachEvent("on"+type, callback, false);
}
}
function removeListener (type, callback)
{
if (document.removeEventListener) {
document.removeEventListener(type, callback, false);
} else if (document.detachEvent) {
document.detachEvent("on" + type, callback, false);
}
}
function handleDown(e)
{
var e = new MouseEvent(e);
addListener("mousemove", handleMove);
addListener("mouseup", handleUp);
offsetX = e.x - parseInt(e.target.style.left);
offsetY = e.y - parseInt(e.target.style.top);
document.getElementById("targetDiv").innerHTML = "";
}
function handleMove(e)
{
var e = new MouseEvent(e);
var x = e.x - offsetX;
e.target.style.left = x + "px";
var y = e.y - offsetY;
e.target.style.top = y + "px";
}
function handleUp(e)
{
var e = new MouseEvent(e);
removeListener("mousemove", handleMove);
removeListener("mouseup", handleUp);
var target = document.getElementById("target");
var x = parseInt(target.style.left);
var y = parseInt(target.style.top);
var width = parseInt(target.style.width);
var height = parseInt(target.style.height);
if(e.x > x && e.x < x + width &&
e.y > y && e.y < y + height){
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new
ActiveXObject("Microsoft.XMLHTTP");
}
if(XMLHttpRequestObject) {
XMLHttpRequestObject.open("GET", "text.txt");
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
document.getElementById("targetDiv").innerHTML =
XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
}
</script>
</head>
<body>
<h1>Buy a television by dragging it to the shopping cart</h1>
<div id="targetDiv"></div>
<div id="television"
style="left:200px; top:100px; width:80px; height:80px;"
onmousedown="handleDown(event);">Television</div>
<div id="target"
style="left:300px; top:300px; width:200px; height:100px;">
Shopping Cart</div>
</body>
</html>
Ajax for Web Application Developers
Ajax for Web Application Developers provides the in-depth working knowledge of Ajax that web developers need to take their web applications to the next level. I will show you how to create an Ajax-driven web application from an object-oriented perspective, and it includes discussion of several useful Ajax design patterns.
This detailed Ajax Training covers the creation of connections to a MySQL database with PHP 5 via a custom Ajax engine and shows how to gracefully format the response with CSS, JavaScript, and XHTML while keeping the data tightly secure. It also covers the use of four custom Ajax-enabled components in an application and how to create each of them from scratch.
This AJAX Training combines the individual code examples and techniques, Ajax-driven application an internal web mail application that can be used in any user-based application, such as a community-based web application. You will learn not only how to create and use their own reusable Ajax components in this application
but also how to connect their components to any future Ajax applications that they might build.
formprocessing - index.php - AJAX Search Code
<html>
<head>
<title>CowAJAX::Form Processing Example</title>
<script language="javascript" type="text/javascript" src="../../js/ajax.lib.js"></script>
<script language="javascript" type="text/javascript" src="../../js/dhtml.lib.js"></script>
<style type="text/css">
body {font-family: verdana, arial;
font-size: 12px;
overflow: hidden;
}
h1 {font-size: 16px; margin: 0px;}
#form1 {width: 45%;
position: absolute;
top: 50px;
}
#form2 {width: 45%;
margin-left: 50%;
position: absolute;
top: 50px;
}
#inner {width: 100%}
form {margin: 0px;
padding: 8px;
border: 12px solid gray;
background: #FFF;
color: #000;
}
form div label {display: block;
width: 150px;
text-align: right;
float: left;
}
.fieldbox {border: 1px solid #4EAE4E;
background-color: #EEFFEE;
padding: 3px;
margin-bottom: 4px;
}
.fieldbox span{color: #4EAE4E;}
</style>
<script>
window.history.back = function() {
}
</script>
</head>
<body>
<!-- Start of Form Processing -->
<h1>Form Processing Example...</h1>
<br />
<div id="form1">
<form method="post" action="controller.php" name="form1">
<div id="inner">
<div class="fieldbox">
<label>Text Field 1:</label>
<input type="text" name="textfield1"/>
</div>
<div class="fieldbox">
<label>Text Field 2:</label>
<input type="text" name="textfield2" />
</div>
<div class="fieldbox">
<label>Textarea:</label>
<textarea name="textarea" cols="38" rows="4"></textarea>
</div>
<div class="fieldbox">
<label>Checkboxes:</label>
<input type="checkbox" name="checxkbox1" />1
<input type="checkbox" name="checxkbox2" />2
<input type="checkbox" name="checxkbox3" />3
<input type="checkbox" name="checxkbox4" />4
</div>
<div class="fieldbox">
<label>Radio Buttons:</label>
<input type="radio" name="radiobutton" value="1"/>Yes
<input type="radio" name="radiobutton" value="0"/>No
</div>
<div class="fieldbox">
<label>Dropdown List (select):</label>
<select name="select">
<option value="0">--Select Option--</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
</div>
<div class="fieldbox">
<label>Multiple Select:</label>
<select name="multiple[]" multiple="multiple">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
</div>
<input type="button" name="submitForm1" value="Submit >>" style="float: right; margin-left: 6px;"/>
<input type="reset" name="reset" value="Reset" style="float: right"/>
<div style="clear: both"></div>
</div>
</form>
</div>
<div id="form2">
<form method="post" action="controller.php" name="form2">
<div id="inner">
<div class="fieldbox">
<label>Text Field 1:</label>
<input type="text" name="textfield1"/>
</div>
<div class="fieldbox">
<label>Text Field 2:</label>
<input type="text" name="textfield2" />
</div>
<div class="fieldbox">
<label>Textarea:</label>
<textarea name="textarea" cols="38" rows="4"></textarea>
</div>
<div class="fieldbox">
<label>Checkboxes:</label>
<input type="checkbox" name="checxkbox1" />1
<input type="checkbox" name="checxkbox2" />2
<input type="checkbox" name="checxkbox3" />3
<input type="checkbox" name="checxkbox4" />4
</div>
<div class="fieldbox">
<label>Radio Buttons:</label>
<input type="radio" name="radiobutton" value="1"/>Yes
<input type="radio" name="radiobutton" value="0"/>No
</div>
<div class="fieldbox">
<label>Dropdown List (select):</label>
<select name="select">
<option value="0">--Select Option--</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
</div>
<div class="fieldbox">
<label>Multiple Select:</label>
<select name="multiple[]" multiple="multiple">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
</div>
<input type="button" name="submitForm2" value="<< Submit"/>
<input type="reset" name="reset" value="Reset"/>
<div style="clear: both"></div>
</div>
</form>
</div>
<!-- End of Form Processing -->
<!-- ######################## -->
<!-- Start of PHP source -->
<br />
<b><u>PHP Code</u></b>
<div style="margin-top: 4px; width: 45%; overflow: auto; height: 150px; border: 1px solid gray; border-style: inset; position: absolute; top: 500px; left: 10px;">
<?php
highlight_file('controller.php');
?>
</div>
<!-- End of PHP source -->
</body>
</html>
formprocessing - controller.php - AJAX Search Code
require_once('../../lib/xmlajaxresponse.class.php');
require_once('../../lib/request.class.php');
$response = &new XMLAjaxResponse();
$request = &new HttpRequest();
$event = $request->getParameter('event');
if ($event && function_exists($event)) {
$event($request, $response);
}
function submitForm1(&$request, &$response) {
$response->addForm('form2', $request->getParameters());
}
function submitForm2(&$request, &$response) {
$response->addForm('form1', $request->getParameters());
}
$response->doResponse();
?>
form - index.php - AJAX Code Search
<html>
<head>
<title>CowAJAX::Registration Form Example</title>
<script language="javascript" type="text/javascript" src="../../js/ajax.lib.js"></script>
<script language="javascript" type="text/javascript" src="../../js/dhtml.lib.js"></script>
<style type="text/css">
body {font-family: verdana, arial;
font-size: 12px;
overflow: hidden;
}
h1 {font-size: 16px; margin: 0px;}
#main {width: 45%}
#inner {width: 100%}
form {margin: 0px;
padding: 8px;
border: 12px solid gray;
background: #FFF;
color: #000;
}
form div label {display: block;
width: 150px;
text-align: right;
float: left;
}
.fieldbox {border: 1px solid #4EAE4E;
background-color: #EEFFEE;
padding: 3px;
margin-bottom: 4px;
}
.fieldbox span{color: #4EAE4E;}
.fieldboxerror {padding: 3px;
margin-bottom: 4px;
border: 1px solid #880000;
background-color: #ffeeee;
}
.fieldboxerror span{color: #FF0000;}
.erroralert {padding: 6px;
text-align: center;
margin-bottom: 12px;
border: 4px solid #880000;
background-color: #FFF4D8;
color: red;
}
#successalert {padding: 8px;
border: 12px solid gray;
background: #EEEAEA;
color: #000000;
}
#message {display: none;}
</style>
</head>
<body>
<!-- Start of Registration Form -->
<h1>Registration Form Example...</h1>
<br />
<div id="main">
<form method="post" action="controller.php">
<div id="inner">
<div id="message" class="erroralert"></div>
<div id="firstnamebox" class="fieldbox">
<label>First Name:</label>
<input type="text" name="firstname"/>
<span>*</span>
</div>
<div id="lastnamebox" class="fieldbox">
<label>Last Name:</label>
<input type="text" name="lastname" />
<span>*</span>
</div>
<div id="addressbox" class="fieldbox">
<label>Address:</label>
<input type="text" name="address" />
<span>*</span>
</div>
<div id="emailbox" class="fieldbox">
<label>Email:</label>
<input type="text" name="email" />
<span>*</span>
</div>
<div id="websitebox" class="fieldbox">
<label>Website:</label>
<input type="text" name="website" />
<span>*</span>
</div>
<input type="button" name="submitForm" value="Submit" style="float: right; margin-left: 6px;"/>
<input type="reset" name="reset" value="Reset" style="float: right"/>
<div style="clear: both"></div>
</div>
</form>
</div>
<!-- End of Registration Form -->
<!-- ######################## -->
<!-- Start of PHP source -->
<br />
<b><u>PHP Code</u></b>
<div style="margin-top: 4px; width: 45%; overflow: auto; height: 150px; border: 1px solid gray; border-style: inset">
<?php
highlight_file('controller.php');
?>
</div>
<!-- End of PHP source -->
</body>
</html>
form - controller.php - AJAX Search Code
require_once('../../lib/xmlajaxresponse.class.php');
require_once('../../lib/request.class.php');
$response = &new XMLAjaxResponse();
$request = &new HttpRequest();
$event = $request->getParameter('event');
if ($event && function_exists($event)) {
$event($request, $response);
}
function submitForm(&$request, &$response) {
$firstName = $request->getParameter('firstname');
$lastName = $request->getParameter('lastname');
$address = $request->getParameter('address');
$email = $request->getParameter('email');
$website = $request->getParameter('website');
$errors = array();
if (!$firstName) {
$errors[] = 'First Name is required';
$response->addElement('firstnamebox', 'className', 'fieldboxerror');
} else {
$response->addElement('firstnamebox', 'className', 'fieldbox');
}
if (!$lastName) {
$errors[] = 'Last Name is required';
$response->addElement('lastnamebox', 'className', 'fieldboxerror');
} else {
$response->addElement('lastnamebox', 'className', 'fieldbox');
}
if (!$address) {
$errors[] = 'Address is required';
$response->addElement('addressbox', 'className', 'fieldboxerror');
} else {
$response->addElement('addressbox', 'className', 'fieldbox');
}
if (!$email) {
$errors[] = 'Email is required';
$response->addElement('emailbox', 'className', 'fieldboxerror');
} else {
$response->addElement('emailbox', 'className', 'fieldbox');
}
if (!$website) {
$errors[] = 'Web site is required';
$response->addElement('websitebox', 'className', 'fieldboxerror');
} else {
$response->addElement('websitebox', 'className', 'fieldbox');
}
if ($errors) {
$response->addData('message', implode('<br />', $errors), 'fadeout');
} else {
//$response->addElement('message', 'style.display', 'none');
$response->addData('main', '<div id="successalert"><b>Thank You!</b><br />Registration has been completed.</div>', 'fadeout');
}
}
$response->doResponse();
?>
chessdesk - index.php - AJAX Search Code
<html>
<head>
<title>CowAJAX::Chess Desk Example</title>
<script language="javascript" type="text/javascript" src="../../js/ajax.lib.js"></script>
<script language="javascript" type="text/javascript" src="../../js/dhtml.lib.js"></script>
<style type="text/css">
body {font-family: verdana, arial;
font-size: 12px;
}
#main {border: 1px solid red;
width: 640px;
margin: 0 auto;
overflow: hidden;
}
#main div{height: 80px;
width: 80px;
float: left;
font-size: 16px;
text-align: center;
font-weight: bold;
}
.whitebox {background: #FFF;
color: #000;
}
.blackbox {background: #000;
color: #FFF;
}
#php {width: 640px;
margin: 0 auto;
}
#php div{margin-top: 4px;
overflow: auto;
height: 150px;
border: 1px solid gray;
border-style: inset;
}
</style>
</head>
<body>
<!-- Start of Chess Desk -->
<div style="text-align: center">
<a href="controller.php" name="get.changeDesk"><b>Change Me</b></a>
|
<a href="controller.php" name="get.reloadDesk"><b>Reload Me</b></a>
</div>
<br />
<div id="main">
<?php
$style[] = 'whitebox';
$style[] = 'blackbox';
$j = 0;
$k = 0;
for($i = 0; $i < 64; $i++) {
if ($j == 8) {
$j = 0;
$k = $k == 1 ? 0 : 1;
}
echo "\n\t\t" . '<div id="box' . $i . '" class="' . $style[($j + $k) % 2] . '">' . ($i+1) . '</div>';
$j++;
}
?>
</div>
<!-- End of Chess Desk -->
<!-- ######################## -->
<!-- Start of PHP source -->
<br style="clear: both"/>
<div id="php">
<b><u>PHP Code</u></b>
<div>
<?php
highlight_file('controller.php');
?>
</div>
</div>
<!-- End of PHP source -->
</body>
</html>
chessdesk - controller.php - AJAX Search Code
require_once('../../lib/xmlajaxresponse.class.php');
require_once('../../lib/request.class.php');
$response = &new XMLAjaxResponse();
$request = &new HttpRequest();
$event = $request->getParameter('event');
if ($event && function_exists($event)) {
$event($request, $response);
}
function changeDesk(&$request, &$response) {
$range = range(0, 63);
shuffle($range);
$boxes = array_slice($range, 0, 8);
foreach($boxes as $box) {
$response->addData('box' . $box, 'Changed<br />' . ($box + 1), 'fadeout');
}
}
function reloadDesk(&$request, &$response) {
for($i = 0; $i < 64; $i++) {
$response->addData('box' . $i, ($i + 1));
}
}
$response->doResponse();
?>
controller.php - AJAX Search Code
require_once('../../lib/xmlajaxresponse.class.php');
require_once('../../lib/request.class.php');
$response = &new XMLAjaxResponse();
$request = &new HttpRequest();
$event = $request->getParameter('event');
if ($event && function_exists($event)) {
$event($request, $response);
}
function append(&$request, &$response) {
process($request, $response, 'append');
}
function prepend(&$request, &$response) {
process($request, $response, 'prepend');
}
function process(&$request, &$response, $mode) {
$productCount = $request->getParameter('productCount');
$tpl = '
$productCount += 1;
$data = str_replace('{ID}', $productCount, $tpl);
if ($mode == 'append') {
$response->addDataAppend('tbody', $data, 'fadeout');
} else if ($mode == 'prepend') {
$response->addDataPrepend('tbody', $data, 'fadeout');
}
$response->addElement('productCount', 'value', $productCount);
}
function remove(&$request, &$response) {
$productCount = $request->getParameter('productCount');
$data = $request->getParameter('data');
if ($data) {
foreach($data as $id) {
$productCount -= 1;
$response->addDataRemove('item' . $id, 'fadeout');
}
$response->addElement('productCount', 'value', $productCount);
}
}
$response->doResponse();
?>
index.php - AJAX Search Code
<html>
<head>
<title>CowAJAX::Append, Prepend and Remove Example</title>
<script language="javascript" type="text/javascript" src="../../js/ajax.lib.js"></script>
<script language="javascript" type="text/javascript" src="../../js/dhtml.lib.js"></script>
<style type="text/css">
body {font-family: verdana, arial;
font-size: 12px;
}
#main {border: 1px solid red;
width: 640px;
margin: 0 auto;
overflow: hidden;
}
table {background: #EFEFEF;
width: 640px;
}
table tbody tr {background: #FFF4D8;}
#php {width: 640px;
margin: 0 auto;
}
#php div{margin-top: 4px;
overflow: auto;
height: 150px;
border: 1px solid gray;
border-style: inset;
}
</style>
</head>
<body>
<!-- Start of Example -->
<form method="post" action="controller.php" name="products">
<input type="hidden" name="productCount" id="productCount" value="4" />
<div style="text-align: center">
<a href="controller.php" name="post.append.products"><b>Append Data</b></a>
|
<a href="controller.php" name="post.prepend.products"><b>Prepend Data</b></a>
|
<a href="controller.php" name="post.remove.products"><b>Remove Selected</b></a>
</div>
<br />
<table align="center">
<tbody id="tbody">
<tr id="item1" class="even">
<td width="2%" align="center"><input type="checkbox" name="data[]" value="1"/></td>
<td width="88%">Product Item 1</td>
<td width="10%" align="center">38.89$</td>
</tr>
<tr id="item2" class="odd">
<td width="2%" align="center"><input type="checkbox" name="data[]" value="2"/></td>
<td width="88%">Product Item 2</td>
<td width="10%" align="center">38.89$</td>
</tr>
<tr id="item3" class="even">
<td width="2%" align="center"><input type="checkbox" name="data[]" value="3"/></td>
<td width="88%">Product Item 3</td>
<td width="10%" align="center">38.89$</td>
</tr>
<tr id="item4" class="odd">
<td width="2%" align="center"><input type="checkbox" name="data[]" value="4"/></td>
<td width="88%">Product Item 4</td>
<td width="10%" align="center">38.89$</td>
</tr>
</tbody>
</table>
</form>
<!-- End of Example -->
<!-- ######################## -->
<!-- Start of PHP source -->
<br style="clear: both"/>
<div id="php">
<b><u>PHP Code</u></b>
<div>
<?php
highlight_file('controller.php');
?>
</div>
</div>
<!-- End of PHP source -->
</body>
</html>
index.html - AJAX Search Code
<html>
<head>
<title>CowAJAX Samples</title>
</head>
<body>
<a href="form/">Registration Form</a>
<br />
<a href="formprocessing/">Form Processing</a>
<br />
<a href="chessdesk/">Chess Desk</a>
<br />
<a href="appendprependremove/">Append/Prepend/Remove</a>
</body>
</html>
request.class.php - AJAX Code Search
class HttpRequest {
var $get;
var $post;
var $request;
var $cookie;
var $session;
function HttpRequest() {
$this->get = $_GET;
$this->post = $_POST;
$this->cookie = $_COOKIE;
$this->request = array();
$this->init();
}
function init() {
$valueArrays = array($this->get, $this->post, $this->cookie);
foreach($valueArrays as $valueArray) {
if ($valueArray) {
foreach($valueArray as $paramName=>$paramValue) {
if (!is_array($paramValue)) {
$this->request[$paramName] = addslashes(trim(htmlspecialchars(str_replace('\\', '', $paramValue))));
} else {
foreach($paramValue as $index=>$value) {
$paramValue[$index] = addslashes(trim(htmlspecialchars(str_replace('\\', '', $value))));
}
$this->request[$paramName] = $paramValue;
}
}
}
}
}
function getReferer() {
if (isset($GLOBALS['_SERVER']['HTTP_REFERER'])) {
return $GLOBALS['_SERVER']['HTTP_REFERER'];
}
return null;
}
function getIp() {
if (isset($GLOBALS['_SERVER']['REMOTE_ADDR'])) {
return $GLOBALS['_SERVER']['REMOTE_ADDR'];
}
return null;
}
function getUserAgent() {
if (isset($GLOBALS['_SERVER']['REMOTE_ADDR'])) {
return $GLOBALS['_SERVER']['REMOTE_ADDR'];
}
return null;
}
function getParameter($parameterName) {
return isset($this->request[$parameterName]) ? $this->request[$parameterName] : null;
}
function getParameters() {
return $this->request;
}
function getPostVars() {
return $GLOBALS['_POST'];
}
function getGetVars() {
return $GLOBALS['_GET'];
}
function getRequestVars() {
return $GLOBALS['_REQUEST'];
}
function getCookieVars() {
return $GLOBALS['_COOKIE'];
}
function getSessVars() {
return $GLOBALS['_SESSION'];
}
}
?>
ajaxrequest.class.php - AJAX Code Search
require_once(dirname(__FILE__) . '/request.class.php');
class AjaxRequest extends HttpRequest {
function AjaxRequest() {
parent::HttpRequest();
$this->convertValues($this->request);
}
function convertValues($request) {
if (extension_loaded('iconv')) {
foreach($request as $paramName=>$paramValue) {
if (!is_array($paramValue) && is_string($paramValue)) {
$this->request[$paramName] = iconv("UTF-8", _GLOBAL_ENCODING, $paramValue);
} else if (is_array($paramValue)) {
$this->request[$paramName] = $this->convertValues($paramValue);
}
}
}
}
}
?>
uploadresponse.class.php - AJAX Code Search
class UploadResponse {
var $jsClassName;
var $callBackParams;
var $content;
function UploadResponse() {
$this->jsClassName = null;
$this->callBackParams = array();
$this->content = null;
}
function setJsClassName($jsClassName) {
$this->jsClassName = $jsClassName;
}
function getJsClassName() {
return $this->jsClassName;
}
function setCallBackParams($callBackParams) {
$this->callBackParams = $callBackParams;
}
function getCallBackParams() {
return $this->callBackParams;
}
function addCallBackParam($param, $isString = false) {
if ($isString) {
$param = "'" . $param . "'";
}
$this->callBackParams[] = $param;
}
function setContent($content) {
$this->content = $content;
}
function getContent() {
return $this->content;
}
function doResponse() {
header('Content-Type: text/html; charset=UTF-8');
$params = '';
if ($this->callBackParams) {
$params = ', ' . implode(', ', $this->callBackParams);
}
echo '<html>
<head><title></title></head>
<body>
<pre id="__content_container">' . $this->content . '</pre>
<script language="javascript">
var parentFrame = parent.window;
if (parentFrame) {
var content = document.getElementById("__content_container");
parentFrame.' . $this->jsClassName . '.uploadCallBack(content.innerHTML' . $params . ');
}
</script>
</body>
</html>';
}
}
?>
xmlajaxresponse.class.php - AJAX Code Search
class ResponseData {
var $container;
var $data;
var $type;
var $mode;
var $callBack;
var $fadeTo;
var $fadingColor;
function ResponseData() {
$this->container = null;
$this->data = null;
$this->type = 'text';
$this->mode = null;
$this->callBack = null;
$this->fadeTo = null;
$this->fadingColor = null;
}
function setContainer($container) {
$this->container = $container;
}
function getContainer() {
return $this->container;
}
function setData($data) {
$this->data = $data;
}
function getData() {
return $this->data;
}
function setType($type) {
$this->type = $type;
}
function getType() {
return $this->type;
}
function setMode($mode) {
$this->mode = $mode;
}
function setCallBack($callBack) {
$this->callBack = $callBack;
}
function getCallBack() {
return $this->callBack;
}
function getMode() {
return $this->mode;
}
function setFadeTo($fadeTo) {
$this->fadeTo = $fadeTo;
}
function getFadeTo() {
return $this->fadeTo;
}
function setFadingColor($fadingColor) {
$this->fadingColor = $fadingColor;
}
function getFadingColor() {
return $this->fadingColor;
}
}
class ResponseElement {
var $id;
var $attributes;
var $callback;
function setId($id) {
$this->id = $id;
}
function getId() {
return $this->id;
}
function addAttribute($name, $value) {
$this->attributes[$name] = $value;
}
function getAttribute($name) {
return isset($this->attributes[$name]) ? $this->attributes[$name] : null;
}
function setAttributes($attributes) {
$this->attributes = $attributes;
}
function getAttributes() {
return $this->attributes;
}
function setCallBack($callBack) {
$this->callBack = $callBack;
}
function getCallBack() {
return $this->callBack;
}
}
class XMLAjaxResponse {
var $status;
var $messages;
var $forms;
var $data;
var $encoding;
var $elements;
function XMLAjaxResponse($encoding = 'UTF-8') {
$this->status = true;
$this->messages = array();
$this->forms = array();
$this->data = array();
$this->encoding = $encoding;
}
function setStatus($status) {
$this->status = $status;
}
function getStatusMessage() {
return $this->status ? 'ok' : 'error';
}
function addMessage($message) {
$this->messages[] = $message;
}
function addForm($name, $form) {
$this->forms[$name] = $form;
}
function addData($container, $data, $fadeTo = null, $dom = false) {
$responseData = &new ResponseData();
$responseData->setContainer($container);
$responseData->setData($data);
$responseData->setFadeTo($fadeTo);
if ($dom) $responseData->setType('dom');;
$this->data[] = $responseData;
}
function addDataAppend($container, $data, $fadeTo = null) {
$responseData = &new ResponseData();
$responseData->setContainer($container);
$responseData->setData($data);
$responseData->setType('dom');
$responseData->setMode('append');
$responseData->setFadeTo($fadeTo);
$this->data[] = $responseData;
}
function addDataPrepend($container, $data, $fadeTo = null) {
$responseData = &new ResponseData();
$responseData->setContainer($container);
$responseData->setData($data);
$responseData->setType('dom');
$responseData->setMode('prepend');
$responseData->setFadeTo($fadeTo);
$this->data[] = $responseData;
}
function addDataRemove($id, $fadeTo = null) {
$responseData = &new ResponseData();
$responseData->setContainer($id);
$responseData->setType('dom');
$responseData->setMode('remove');
$responseData->setFadeTo($fadeTo);
$this->data[] = $responseData;
}
function addDataObject($dataObject) {
$this->data[] = $dataObject;
}
function addElement($id, $attributeName, $attributeValue, $callback = null) {
$element = &new ResponseElement();
$element->setId($id);
$element->addAttribute($attributeName, $attributeValue);
$element->setCallback($callback);
$this->elements[] = $element;
}
function addElementObject($element) {
$this->elements[] = $element;
}
function getResponseXml() {
$messages = $this->messages;
$forms = $this->forms;
$responseData = $this->data;
$elements = $this->elements;
$buffer = ob_get_contents();
if ($buffer) {
$dataItems['phperror'] = $buffer;
ob_end_clean();
}
$xml = array();
$xml[] = '<response status="' . $this->getStatusMessage() . '">';
if ($messages) {
$xml[] = ' <messages>';
foreach($messages as $message) {
$xml[] = ' <message><![CDATA[' . $message . ']]></message>';
}
$xml[] = ' </messages>';
}
if ($forms) {
$xml[] = ' <forms>';
foreach($forms as $formName=>$form) {
$xml[] = ' <form name="' . $formName . '">';
$xml[] = ' <elements>';
foreach($form as $fieldName=>$fieldValue) {
if (!is_array($fieldValue)) {
$xml[] = ' <element name="' . $fieldName . '"><![CDATA[' . $fieldValue . ']]></element>';
} else {
$xml[] = ' <element name="' . $fieldName . '">';
foreach($fieldValue as $value) {
$xml[] = ' <value><![CDATA[' . $value . ']]></value>';
}
$xml[] = ' </element>';
}
}
$xml[] = ' </elements>';
$xml[] = ' </form>';
}
$xml[] = ' </forms>';
}
if ($responseData) {
$xml[] = ' <data>';
foreach($responseData as $data) {
$type = $data->getType();
if ($type == 'text') {
$xml[] = ' <item container="' . $data->getContainer() . '" type="' . $type . '" mode="' . $data->getMode() . '" callBack="' . $data->getCallBack() . '" fadeTo="' . $data->getFadeTo() . '" fadingColor="' . $data->getFadingColor() . '"><![CDATA[' . $data->getData() . ']]></item>';
} else if ($type == 'dom') {
$xml[] = ' <item container="' . $data->getContainer() . '" type="' . $type . '" mode="' . $data->getMode() . '" callBack="' . $data->getCallBack() . '" fadeTo="' . $data->getFadeTo() . '" fadingColor="' . $data->getFadingColor() . '">' . $data->getData() . '</item>';
}
}
$xml[] = ' </data>';
}
if ($elements) {
$xml[] = ' <elements>';
foreach($elements as $element) {
$xml[] = ' <element id="' . $element->getId() . '" callBack="' . $element->getCallBack() . '">';
$xml[] = ' <attributes>';
$attributes = $element->getAttributes();
foreach($attributes as $name=>$value) {
$xml[] = ' <attribute attributeName="' . $name . '" attributeValue="' . $value . '"/>';
}
$xml[] = ' </attributes>';
$xml[] = ' </element>';
}
$xml[] = ' </elements>';
}
$xml[] = '</response>';
return implode("\n", $xml);
}
function doResponse() {
header("Content-Type: text/xml; charset=" . $this->encoding);
echo $this->getResponseXml();
}
function reset() {
$this->XMLAjaxResponse();
}
function destroy() {
$this = null;
}
}
?>
event.js - AJAX Search Code
get: function(e) {
return window.event ? window.event : e;
},
getTarget: function(e) {
return e.target || e.srcElement;
},
add: function(obj, evt, fnc, capture) {
if (obj.addEventListener) {
obj.addEventListener(evt, fnc, capture);
return true;
} else if (obj.attachEvent) {
return obj.attachEvent('on' + evt, fnc);
} else {
obj['on' + evt] = fnc;
}
},
remove: function(obj, evt, fnc, capture) {
if (obj.removeEventListener) {
obj.removeEventListener(evt, fnc, capture);
} else if (obj.detachEvent) {
obj.detachEvent('on' + evt, fnc);
} else {
obj['on' + evt] = null;
}
},
addOnLoad: function(fnc) {
var oldOnLoad = window.onload;
if (typeof window.onload != 'function') {
window.onload = fnc;
} else {
window.onload = function() {
oldOnLoad();
fnc();
}
}
}
};
lightbox.js - AJAX Code Search
target: null,
show: function(obj) {
var div = $('lightbox');
if (!div) {
div = document.createElement('div');
div.id = 'lightbox';
var css = new Array();
css[css.length] = 'position: absolute';
css[css.length] = 'top: 0px';
css[css.length] = 'left: 0px';
css[css.length] = 'display: block';
css[css.length] = 'background-color: #000000';
css[css.length] = 'z-index: 9999';
css[css.length] = 'opacity: 0.7';
css[css.length] = 'MozOpacity: 0.7';
css[css.length] = 'KhtmlOpacity: 0.7';
css[css.length] = "filter: alpha(opacity=70)";
div.style.cssText = css.join(';');
document.body.appendChild(div);
}
this.target = obj;
obj.style.display = 'block';
div.style.display = 'block';
div.style.width = getDocumentWidth() + 'px';
div.style.height = getDocumentHeight() + 'px';
},
hide: function() {
if (this.target) {
this.target.style.display = 'none';
}
$('lightbox').style.display = 'none';
}
};
dhtml.lib.js - AJAX Code Search
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// VERSION 0.1
/**
* @fileoverview Cross browser implementation of various DHTML methods
* @author J. Woodo phpcow at gmail.com
* @version 0.1
*/
var Dhtml = {
isOpera: navigator.userAgent.toLowerCase().indexOf('opera') > -1,
getStyle: function(obj, styleName) {
var style = null;
var t = obj.offsetTop;
if (obj.style[styleName]) {
} else if (obj.currentStyle) {
style = obj.currentStyle[styleName];
} else if (window.getComputedStyle) {
style = document.defaultView.getComputedStyle(obj,null).getPropertyValue(styleName);
}
return style;
},
getObjectTop: function (obj) {
var top = 0;
while(obj) {
if (obj.offsetTop) {
if (!this.isOpera) {
var borderWidth = parseInt(this.getStyle(obj.offsetParent, 'borderTopWidth')) || parseInt(this.getStyle(obj.offsetParent, 'border-top-width'));
if (!isNaN(borderWidth)) {
top += borderWidth;
}
}
if (obj.scrollTop && obj.scrollTop > 0) {
top -= obj.scrollTop;
}
top += obj.offsetTop;
} else if (obj.x) {
top += obj.x;
}
obj = obj.offsetParent;
}
return top;
}, getObjectLeft: function (obj) {
var left = 0;
while (obj) {
if (obj.offsetLeft) {
if (!this.isOpera) {
var borderWidth = parseInt(this.getStyle(obj.offsetParent, 'borderLeftWidth')) || parseInt(this.getStyle(obj.offsetParent, 'border-left-width'));
if (!isNaN(borderWidth)) {
left += borderWidth;
}
}
left += obj.offsetLeft;
} else if (obj.y) {
left += obj.y;
}
obj = obj.offsetParent;
}
return left;
}, getObjectWidth: function (obj) {
var width = 0;
if (obj) {
if (obj.offsetWidth) {
width = obj.offsetWidth;
} else if (obj.clip && obj.clip.width) {
width = obj.clip.width;
} else if (obj.style && obj.style.pixelWidth) {
width = obj.style.pixelWidth;
}
}
return parseInt(width);
}, getObjectHeight: function (obj) {
var height = 0;
if (obj) {
if (obj.offsetHeight) {
height = obj.offsetHeight;
} else if (obj.clip && obj.clip.Height) {
height = obj.clip.Height;
} else if (obj.style && obj.style.pixelHeight) {
height = obj.style.pixelHeight;
}
}
return parseInt(height);
}, getObjectXY: function (obj) {
return {x: this.getObjectLeft(obj), y: this.getObjectTop(obj)};
}, getMouseXY: function(e) {
var mouseX, mouseY;
if (window.event) {
e = window.event;
mouseX = e.clientX;
mouseY = e.clientY;
if(document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft)) {
mouseX += document.documentElement.scrollLeft;
mouseY += document.documentElement.scrollTop;
} else if(document.body && (document.body.scrollTop || document.body.scrollLeft)) {
mouseX += document.body.scrollLeft;
mouseY += document.body.scrollTop;
}
} else if(e) {
if(typeof(e.pageX) == 'number') {
mouseX = e.pageX;
mouseY = e.pageY;
} else {
mouseX = e.clientX;
mouseY = e.clientY;
}
}
return {x: mouseX, y: mouseY};
}, getParent: function(obj, parentTagName) {
var parentNode = obj.parentNode;
while(parentNode) {
if (parentNode.tagName == parentTagName.toUpperCase()) {
return parentNode;
}
parentNode = parentNode.parentNode;
}
}
}
drag.js - AJAX Code Search
start: function(e, el, back) {
e = Event.get(e);
el.oldCssText = el.style.cssText;
var objXY = Dhtml.getObjectXY(el);
var startXY = Dhtml.getMouseXY(e);
var deltaXY = {};
deltaXY.x = startXY.x - objXY.x;
deltaXY.y = startXY.y - objXY.y;
Event.add(document, 'mousemove', move, true);
Event.add(document, 'mouseup', up, true);
try {
e.stopPropagation();
e.preventDefault();
} catch(ex) {
e.preventDefault = true;
}
function move(e) {
dragable = null;
var mouseXY = Dhtml.getMouseXY(e);
if (mouseXY.x < startXY.x - 5 ||
mouseXY.x > startXY.x + 5 ||
mouseXY.y < startXY.y - 5 ||
mouseXY.y > startXY.y + 5) {
dragable = el;
el.style.position = 'absolute';
el.style.opacity = '0.5';
el.style.filter = "alpha(opacity=50)";
el.style.left = (mouseXY.x - deltaXY.x) + "px";
el.style.top = (mouseXY.y - deltaXY.y) + 15 + "px";
try {
e.stopPropagation();
e.preventDefault();
} catch(ex) {
e.preventDefault = true;
Event.add(document, 'selectstart', function() {return false;});
Event.add(document, 'drag', function() {return false;});
}
}
}
function up(e) {
Event.remove(document, 'mousemove', move, true);
Event.remove(document, 'mouseup', up, true);
var top = el.style.top;
var left = el.style.left;
el.style.cssText = el.oldCssText;
el.oldCssText = null;
if (!back) {
el.style.top = top;
el.style.left = left;
}
try {
e.stopPropagation();
e.preventDefault();
} catch(ex) {
e.preventDefault = true;
Event.remove(document, 'selectstart', function() {return false;});
Event.remove(document, 'drag', function() {return false;});
}
}
}
}
ajax.lib.js - AJAX Code Search
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// VERSION 0.1
/**
* @fileoverview file contains four main classess for handling request/response between client and server:
* <br />1) XmlHttpRequst - for handling asynchronous requests to server;
* <br />2) XmlHttpResponse - for precessing returned data by XmlHttpRequest class.
* <br />3) AjaxAction - for building correct URL strings;
* <br />4) Ajax - implementation for easy XmlHttpRequst and XmlHttpResponse interaction;
* @author J. Woodo phpcow at gmail.com
* @version 0.1
*/
/**
* Create a new XmlHttpRequest instance.
* @class XmlHttpRequest class.
* Wrapper class for <b>XMLHttpRequest</b>
* @constructor
* @return a new instance of XmlHttpRequest
* @author J. Woodo
* @version 0.1
*/
function XmlHttpRequest() {
/**
* Ready state UNINITIALIZED - open() has not been called yet.
* @public
* @int
*/
this.UNINITIALIZED = 0;
/**
* Ready state LOADING - send() has not been called yet.
* @public
* @int
*/
this.LOADING = 1;
/**
* Ready state LOADED - send() has been called, headers and status are available.
* @public
* @int
*/
this.LOADED = 2;
/**
* Ready state INTERACTIVE - Downloading, responseText holds the partial data.
* @public
* @int
*/
this.INTERACTIVE = 3;
/**
* Ready state COMPLETED - Finished with all operations.
* @public
* @int
*/
this.COMPLETE = 4;
/**
* HTML form default enctype.
* @public
* @string
*/
this.ENCTYPE_GENERAL = "application/x-www-form-urlencoded";
/**
* HTML form multipart enctype.
* @public
* @string
*/
this.ENCTYPE_MULTIPART = "multipart/form-data";
/**
* Stores instantiated XMLHttpRequest object.
* @private
* @XMLHttpRequest
*/
var request = null;
/**
* Stores XMLHttpRequest object's current ready state.
* @private
* @int
*/
var state = 0;
/**
* Array of handlres according to each ready state index.
* @private
* @Array
* @see #addHandler
* @see #runHandlers
*/
var handlers = new Array();
/**
* Default enctype used for request.
* @private
* @int
*/
var enctype = this.ENCTYPE_GENERAL;
/**
* Array of parameters which must be exluded from request.
* @private
* @Array
*/
var excludeParams = new Array();
/**
* Parameters encoding method.
* @private
* @void
* @see #formToParams
*/
var encode = encodeURIComponent;
/**
* Exclude field from HTML form
* @public
* @param {String} name of HTML form element
* @see #formToParams
*/
this.excludeParam = function(paramName) {
excludeParams[paramName] = paramName;
}
/**
* Resets excluded HTML form elements array,
* method is needed if application uses only one instance of XmlHttpRequest class
* @public
*/
this.resetExcludeParams = function() {
excludeParams = new Array();
}
/**
* Main method wich sends request to server
* @public
* @param {String} url of the server side script which will process request
* @param {String} prepared string of parameters (param1=value1¶m2=value2 etc...)
* @param {String} method to be used for HTTP request e.g. POST, GET...
* @see #getHttpRequest
* @see #doGet
* @see #doPost
*/
this.doRequest = function(url, params, method) {
if (!method) {
method = "POST";
}
var req = null;
if (!request) {
req = this.getHttpRequest();
} else {
req = request;
}
if (req) {
state = this.LOADING;
this.runHandlers(this.LOADING);
var obj = this;
req.open(method, url, true);
req.onreadystatechange = function() {
obj.onReadyState();
}
req.setRequestHeader("content-type", enctype);
req.send(params);
request = req;
}
}
/**
* Instantiates new XMLHttpRequest or Microsoft.XMLHTTP object
* @public
* @see #doRequest
* @returns XMLHttpRequest object
*/
this.getHttpRequest = function() {
var request = null;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
return request;
}
/**
* function for XMLHttpRequest onreadystatechange event handler
* @public
* @see #doRequest
* @see #addHandler
* @see #runHandlers
*/
this.onReadyState = function() {
if (request) {
state = request.readyState;
}
this.runHandlers(state);
}
/**
* Loops trough handlers Array and evaluates items according to XMLHtppRequest state
* @public
* @param {int} state
* @see #addHandler
* @see #onReadyState
*/
this.runHandlers = function(state) {
if (handlers[state]) {
var _handlers = handlers[state];
for (var key in _handlers) {
try {
eval(_handlers[key] + "()");
} catch (e) {
//alert(e.message);
}
}
}
}
/**
* Adds new handler for apropriate state
* @public
* @param {String} name of handler
* @param {int} state
* @see #addHandler
* @see #onReadyState
*/
this.addHandler = function(name, state) {
if (!state) {
state = this.COMPLETE;
}
if (!handlers[state]) {
handlers[state] = new Array();
}
if (!handlers[state][name]) {
handlers[state][name] = name;
}
}
/**
* Checks wheather handler exists or not
* @public
* @param {String} name of handler
* @see #runHanlders
*/
this.hasHandler = function(name) {
return handlers[name];
}
/**
* Resets handlers array.
* method is needed if application uses only one instance of XmlHttpRequest class
* @public
* @see #addHandler
*/
this.resetHandlers = function() {
handlers = new Array();
}
/**
* Performs HTTP POST request.
* @public
* @requires {@link AjaxAction} AaxAction class
* @param {AjaxAction} AjaxAction instance
* @param {Form} HTML form element
* @see #doRequest
* @see #formToParams
*/
this.doPost = function(url, form) {
var formParams = this.formToParams(form);
var _url = (typeof(url) == 'object') ? url.getUrl() : url;
var idx = _url.indexOf('?');
if (idx > -1) {
if (formParams) {
if (formParams.substr(formParams.length - 1) != "&") {
formParams += "&";
}
}
formParams += _url.substr(idx + 1);
}
this.doRequest(_url, formParams, "POST");
}
/**
* Performs HTTP GET request.
* @public
* @param {AjaxAction} AjaxAction instance
* @param {Form} HTML form element
* @see #doRequest
* @see #formToParams
*/
this.doGet = function(url, form) {
var ulrStr = typeof(url) == 'object' ? url.getUrl() : url;
if (ulrStr.indexOf('?') == -1) {
ulrStr += '?';
}
this.doRequest(ulrStr + '&' + this.formToParams(form), null, "GET");
}
/**
* Returns response text
* @public
* @returns String
*/
this.getText = function() {
return request.responseText;
}
/**
* Returns response XML document
* @public
* @returns XML DOM document
*/
this.getXml = function() {
return request.responseXML;
}
/**
* Transform HTML form element to request parameter string e.g. param1=value1¶m2=value2 etc...
* @public
* @returns String
*/
this.formToParams = function(form) {
var params = '';
var type = null;
if (form) {
for (var i = 0; i<form.length; i++) {
if (!excludeParams[form[i].name] && form[i].name) {
type = form[i].type;
if (type == 'checkbox' || type == 'radio') {
if (form[i].checked) {
params += form[i].name + "=" + encode(form[i].value);
} else {
if (type == 'checkbox') {
params += form[i].name + "=";
}
}
} else if (type == 'select-one') {
if (!form[i].value && form[i].options.length > 0) {
params += form[i].name + "=" + encode(form[i].options[form[i].selectedIndex].text);
} else {
params += form[i].name + "=" + encode(form[i].value);
}
} else if (type == 'select-multiple') {
var opts = form[i].options;
var optParamValue = new Array();
for (var j=0; j<opts.length; j++) {
if (opts[j].selected) {
optParamValue[j] = form[i].name + "=" + encode((opts[j].getAttribute("value") || opts[j].text));
}
}
if (optParamValue.length > 0) {
params += optParamValue.join("&");
}
} else {
if (type != 'button' && type != 'reset' && type != 'file' && type != undefined) {
params += form[i].name + "=" + encode(form[i].value);
}
}
if ((i+1) < form.length && params.substr(params.length - 1) != '&') {
params += "&";
}
}
}
}
return params;
}
}
/**
* Create a new XmlHttpResponse instance. Class is used for processing server response.
* @class XmlHttpResponse class.
* @constructor
* @return a new instance of XmlHttpResponse
* @requires {@link Fader} Fader class
* @author J. Woodo
* @version 0.1
*/
var XmlHttpResponse = function() {
/**
* Array of instantiated Fader objects.
* @private
*/
var faders = new Array();
/**
* Target object to fade
* @private
*/
var faderTarget = null;
/**
* Processes response XML and performs method calls according to XML document.
* @public
* @param {XmlDomDocument} XML DOM document
* @returns void
*/
this.process = function(xml) {
var elements = xml.getElementsByTagName("elements");
if (elements && elements[0]) {
this.processElements(elements[0]);
}
var data = xml.getElementsByTagName("data");
if (data && data[0]) {
this.processData(data[0]);
Ajax.initializeElements();
}
var htmlForms = xml.getElementsByTagName("forms");
if (htmlForms && htmlForms[0]) {
this.processForms(htmlForms[0]);
}
xml = null;
}
/**
* Assigns styles to HTML elements defined under <elements> node
* @public
* @param XmlDomDocument
* @return void
*/
this.processElements = function(elements) {
var element = null;
var id;
var elementList = elements.getElementsByTagName("element");
if (elementList) {
for (var i = 0; i < elementList.length; i++) {
element = elementList[i];
id = element.getAttribute('id');
var obj = document.getElementById(id);
if (obj) {
var attributeList = element.getElementsByTagName('attributes').item(0);
if (attributeList) {
var attributes = attributeList.getElementsByTagName('attribute');
if (attributes) {
for (var j = 0; j < attributes.length; j++) {
eval("obj." + attributes[j].getAttribute("attributeName") + "=attributes[j].getAttribute('attributeValue')");
}
}
}
}
}
}
}
/**
* Processes <data> node and renderes returned HTML data.
* @public
* @param DOM element
* @see #processDom
* @returns void
*/
this.processData = function(data) {
try {
var items = data.getElementsByTagName("item");
if (items) {
var html = null;
var type = null;
var mode = null;
var callBack = null;
var fader = null;
var fadeTo = null;
var fadingColor = null;
var containerName = null;
var container = null;
cleanUpFaders();
for(var i = 0; i<items.length; i++) {
containerName = items[i].getAttribute("container");
type = items[i].getAttribute("type");
mode = items[i].getAttribute("mode");
callBack = items[i].getAttribute("callBack");
fadeTo = items[i].getAttribute("fadeTo");
fadingColor = items[i].getAttribute("fadingColor");
container = document.getElementById(containerName);
if (container) {
if (callBack) {
eval(callBack + "(items[i])");
} else {
if (type == 'text' && items[i].firstChild.nodeType == 4) {
container.style.display = "block";
container.innerHTML = items[i].firstChild.nodeValue;
} else if (type && type == 'dom') {
if (mode != 'append' && mode != 'prepend' && mode != 'remove') {
while(container.firstChild) {
container.removeChild(container.firstChild);
}
}
if (mode == 'remove') {
fadeElement(fadeTo, container, fadingColor);
//container.parentNode.removeChild(container);
fadeTo = null;
} else {
this.processDom(container, items[i].childNodes, mode);
}
}
fadeElement(fadeTo, faderTarget ? faderTarget : container, fadingColor);
}
}
}
}
} catch(e) {
error = false;
alert(e.message);
}
}
/**
* Processes <data> node and builds part of document using JavaScript DOM functions.
* @public
* @param HTML element (container)
* @param DOM elements
* @see #processData
* @returns Object
*/
this.processDom = function(container, elements, mode) {
var tmpElem = null;
var tmpText = null;
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element.nodeType == 1) {
tmpElem = document.createElement(element.tagName);
applyAttributes(tmpElem, element.attributes);
if (element.hasChildNodes()) {
this.processDom(tmpElem, element.childNodes, mode);
}
if (mode == 'append' || mode == 'prepend') {
faderTarget = tmpElem;
}
if (mode == 'prepend') {
container.insertBefore(tmpElem, container.firstChild);
mode = null;
faderTarget = tmpElem;
} else {
container.appendChild(tmpElem);
}
} else if (element.nodeType == 3 || element.nodeType == 4) {
tmpText = document.createTextNode(element.nodeValue);
container.appendChild(tmpText);
}
}
return container;
}
/**
* Processes <forms> node.
* @public
* @param DOM element
* @returns void
*/
this.processForms = function(htmlForms) {
htmlForms = htmlForms.getElementsByTagName('form');
var htmlForm = null;
var formName = null;
var form = null;
var elementList = null;
var elements = null;
for (var i = 0; i < htmlForms.length; i++) {
htmlForm = htmlForms[i];
formName = htmlForm.getAttribute('name');
if (formName) {
if (form = document.forms[formName]) {
if (elementList = htmlForm.getElementsByTagName('elements')) {
elements = elementList[0].getElementsByTagName('element');
if (elements) {
this.processForm(form, elements);
}
}
}
}
}
}
/**
* Processes <form> nodes and assigns values to apropriate HTML form fields.
* @public
* @param DOM element
* @returns void
*/
this.processForm = function(form, elements) {
try {
var element = null;
var fieldName = null;
var selectValue = null;
var selectOpts = null;
for (var i=0; i < elements.length; i++) {
element = elements[i];
fieldName = element.getAttribute('name');
var field = form[fieldName] || form[fieldName+"[]"];
if (field) {
if (field.type == 'select-one') {
selectOpts = field.options;
var xmlOptValue = element.firstChild.nodeValue;
for (var j=0; j<selectOpts.length; j++) {
selectValue = selectOpts[j].value || selectOpts[j].text;
selectOpts[j].selected = (selectValue == xmlOptValue);
}
} else if (field.type == 'select-multiple') {
selectOpts = field.options;
var xmlOpts = element.getElementsByTagName('value');
if (xmlOpts) {
var usedOpts = new Array();
for (var j=0; j < xmlOpts.length; j++) {
var xmlOptValue = xmlOpts[j].firstChild.nodeValue;
for (var k=0; k<selectOpts.length; k++) {
selectValue = selectOpts[k].value || selectOpts[k].text;
if (selectValue == xmlOptValue && !usedOpts[k]) {
usedOpts[k] = selectValue;
selectOpts[k].selected = true;
} else if (!usedOpts[k]) {
selectOpts[k].selected = false;
}
}
}
usedOpts = null;
}
} else if (field.length && field.length > 0) {
for (var j=0; j < field.length; j++) {
if (field[j].type == 'radio') {
if (field[j].value == element.firstChild.nodeValue) {
field[j].checked = true;
} else {
field[j].checked = false;
}
}
}
} else {
if (element.firstChild) {
if (field.type == 'checkbox' || field.type == 'radio') {
if (field.value == element.firstChild.nodeValue) {
field.checked = true;
} else {
field.checked = false;
}
} else {
field.value = element.firstChild.nodeValue;
}
} else {
field.value = '';
}
}
}
}
} catch(e) {
//alert(e.message);
}
}
/**
* Iterates trough attributes array and asigns them to the element.
* @private
* @param DOM element
* @param Array
* @see #applyAttribute
* @returns void
*/
var applyAttributes = function(element, attributes) {
for (var j = 0; j < attributes.length; j++) {
applyAttribute(element, attributes[j].nodeName, attributes[j].nodeValue);
}
}
/**
* Asigns attribute/value pair to element.
* @private
* @param DOM element
* @param {String} Attribute name
* @param {String} Attribute value
* @see #applyAttributes
* @returns void
*/
var applyAttribute = function(element, attributeName, attributeValue) {
if (attributeName == 'class') {
element.className = attributeValue;
} else if (attributeName == 'style') {
element.style.cssText = attributeValue;
} else if (attributeName == 'id') {
element.id = attributeValue;
} else {
element.setAttribute(attributeName, attributeValue);
}
}
/**
* Instantiates and calls one of the Fading methods.
* @private
* @param {String} method name to call
* @param {Object} Html element to fade
* @param {String} Fading start color
* @returns void
*/
var fadeElement = function(fadeTo, container, fadingColor) {
if (fadeTo) {
fader = new Fader(container, fadingColor);
faders[faders.length] = fader;
switch (fadeTo) {
case Fader.FADEIN:
fader.fadeIn();
break;
case Fader.FADEAWAY:
fader.fadeAway();
break;
case Fader.FADEOUT:
fader.fadeOut();
break;
default:
break;
}
}
}
/**
* Destroies instantiated Fader instances.
* @private
* @returns void
*/
var cleanUpFaders = function() {
if (faders) {
for (var i = 0; i < faders.length; i++) {
faders[i].opacity = 10;
}
faders = new Array();
}
}
}
var Ajax = {
/**
* Instance of XmlHttpRequest class
* @public
*/
http: new XmlHttpRequest(),
/**
* Instance of XmlHttpResponse class
* @public
*/
response: new XmlHttpResponse(),
/**
* Instance of Indicator class
* @public
*/
indicator: new Indicator(),
/**
* Performs server call
* @public
* @returns void
*/
doAction: function(obj) {
/*var action = null;
if (obj.href) {
action = obj.href;
} else if (obj.form) {
if (obj.form.action) {
action = obj.form.action;
}
form = obj.form;
}
if (form && typeof(form) == 'string') {
form = document.forms[form];
}
var action = new AjaxAction(action);
action.addParam("event", obj.name.replace('submit.', ''));
this.http.addHandler("Ajax.finish", this.http.COMPLETE);
this.http.doPost(action, form);*/
if (obj.cmd) {
this.indicator.show();
var action = new AjaxAction(obj.cmd.action);
action.addParam("event", obj.cmd.event);
this.http.addHandler("Ajax.finish", this.http.COMPLETE);
if (obj.cmd.method == 'post') {
this.http.doPost(action, obj.cmd.form);
} else {
this.http.doGet(action, obj.cmd.form);
}
}
},
/**
* Finishes response
* @public
* @returns void
*/
finish: function() {
this.response.process(this.http.getXml());
this.indicator.hide();
},
/**
* Initializes HTML anchor and input elements and attach apropriate method calls
* @public
* @returns void
*/
initializeElements: function() {
var anchors = document.getElementsByTagName('a');
var i = 0;
for (; i<anchors.length; i++) {
var anchor = anchors[i];
var href = anchor.getAttribute('href');
var name = anchor.getAttribute('name');
var tmp = null;
var cmd = null;
//get.someEvent.someForm
if (href && name && ((name.indexOf('get.') != -1) || (name.indexOf('post.') != -1) || (name.indexOf('call.') != -1)) && !anchor.onclick) {
tmp = name.split('.');
if (tmp.length >= 2) {
if (tmp[0] == 'call') {
tmp.shift();
anchor.onclick = function() {
return eval(tmp.join('.') + "(this)");
}
} else {
cmd = {};
cmd.action = href;
cmd.method = tmp[0];
cmd.event = tmp[1].toLowerCase();
cmd.form = document.forms[tmp[2]] ? document.forms[tmp[2]] : null;
anchor.cmd = cmd;
anchor.onclick = function() {
Ajax.doAction(this);
return false;
}
}
}
}
/*if (href && name && (name.indexOf('submit.') != -1) && !anchor.onclick) {
anchor.onclick = function() {
Ajax.doAction(this, Dhtml.getParent(anchor, 'form'));
return false;
}
}*/
}
var inputs = document.getElementsByTagName('input');
for (i = 0; i<inputs.length; i++) {
var input = inputs[i];
if (input.getAttribute('type') == 'button' && !input.onclick) {
cmd = {};
cmd.action = input.form.action;
cmd.method = input.form.method.toLowerCase();
cmd.event = input.name;
cmd.form = input.form;
input.cmd = cmd;
input.onclick = function() {
Ajax.doAction(this);
return false;
}
}
}
}
};
/**
* Create a new AjaxAction instance.
* @class AjaxAction class.
* @constructor
* @returns a new instance of AjaxAction
* @author J. Woodo
* @version 0.1
*/
function AjaxAction(action) {
/**
* Associative array of parameters
* @private
* @tepe Array
*/
var params = new Array();
/**
* To prevent IE from caching result each consturcted action string
* has additional _req_date parameter
* @private
* @tepe Date
*/
var date = new Date();
params['_req_date'] = date.getTime();
params.length += 1;
/**
* Builds and Returns action URL.
* @public
* @returns URL
* @type String
* @returns String
*/
this.getUrl = function() {
var keyValues = new Array();
if (params) {
for(var key in params) {
keyValues[keyValues.length] = key + '=' + params[key];
}
}
if (action.indexOf('?') == -1) {
action += '?';
}
if (action.length > 0) {
action += '&';
}
return action + keyValues.join('&');
}
/**
* Adds new request parameter to parameters map.
* @public
* @return void
*/
this.addParam = function(name, value) {
params[name] = value;
params.length += 1;
}
}
/**
* Create a new Indicator instance. Class is used to show some action on page,
* indicator is presented as small red box on the page's right top corner and is visible while some action finishes
* @class Indicator class.
* @constructor
* @return a new instance of Indicator
* @author J. Woodo
* @version 0.1
*/
function Indicator() {
/**
* Displayes indicator on the page
* @public
* @return void
*/
this.show = function() {
var top = 0;
if(document.documentElement && document.documentElement.scrollTop) {
top = document.documentElement.scrollTop;
} else if( document.body && document.body.scrollTop) {
top = document.body.scrollTop;
}
if (document.body) {
document.body.style.cursor = "wait";
}
var div = this.getIndicator();
div.style.top = top + "px";
div.style.display = "block";
}
/**
* Hides indicator when action finished
* @public
* @return void
*/
this.hide = function() {
var div = this.getIndicator();
div.style.display = "none";
if (document.body) {
document.body.style.cursor = "default";
}
}
/**
* Creates (if not exists) and returns indicator HTML element
* @public
* @type Object
* @return void
*/
this.getIndicator = function() {
var indicator = document.getElementById("_indicator");
if (!indicator) {
indicator = document.createElement("div");
indicator.id = "_indicator";
indicator.style.display = "none";
indicator.style.background = "#880000";
indicator.style.padding = "1px";
indicator.style.fontFamily = "arial";
indicator.style.fontSize = "12px";
indicator.style.color = "white";
indicator.style.position = "absolute";
indicator.style.top = "0px";
indicator.style.right = "0px";
var text = document.createTextNode("Processing...");
indicator.appendChild(text);
document.body.appendChild(indicator);
}
return indicator;
}
}
Fader.FADEIN = 'fadein';
Fader.FADEOUT = 'fadeout';
Fader.FADEAWAY = 'fadeaway';
/**
* Create a new Fader instance.
* Class is used to creating various fading effects.
* @class Fader class.
* @constructor
* @param Object - HTML element whic must be faded
* @return a new instance of Fader
* @author J. Woodo
* @version 0.1
*/
function Fader(targetObj, color) {
/**
* Initial opacity value for fading object
* @public
* @type int
*/
this.opacity = 85;
/**
* Stores window interval object
* @private
* @type Object
*/
var interval = null;
/**
* Fading color to be used
* @private
* @type String
*/
var fadingColor = color ? color : '#FDCE5E';
//var fadingColor = color ? color : '#FFFF00';
/**
* Number of milliseconds
* @private
* @type int
*/
var miliseconds = 1;
/**
* Target object to fade
* @private
* @type Object
*/
var faderObj = null;
faderObj = document.getElementById('_fader_' + targetObj.id);
if (!faderObj) {
faderObj = document.createElement('div');
faderObj.id = '_fadertest';
document.body.appendChild(faderObj);
}
var xy = Dhtml.getObjectXY(targetObj);
faderObj.style.zIndex = 9999;
faderObj.style.display = "block";
faderObj.style.position = "absolute";
faderObj.style.top = xy.y + "px";
faderObj.style.left = xy.x + "px";
faderObj.style.background = fadingColor;
faderObj.style.width = Dhtml.getObjectWidth(targetObj) + "px";
faderObj.style.height = Dhtml.getObjectHeight(targetObj) + "px";
/**
* Fades out HTML element
* @public
* @returns void
*/
this.fadeOut = function() {
if (this.opacity > 10) {
this.applyOpacity();
var obj = this;
interval = setTimeout(function() {obj.fadeOut()}, miliseconds);
} else if (this.opacity <= 10) {
this.finish();
}
}
/**
* Fades away HTML element
* @public
* @returns void
*/
this.fadeAway = function() {
if (this.opacity > 10) {
this.applyOpacity();
this.applyOpacity(targetObj);
var obj = this;
interval = setTimeout(function() {obj.fadeAway()}, miliseconds);
} else if (this.opacity <= 10) {
targetObj.parentNode.removeChild(targetObj);
this.finish();
}
}
/**
* Sets calculated opacity to object
* @public
* @return void
*/
this.applyOpacity = function(obj) {
var style = obj || faderObj.style;
style.opacity = (this.opacity / 100);
style.MozOpacity = (this.opacity / 100);
style.KhtmlOpacity = (this.opacity / 100);
style.filter = "alpha(opacity=" + this.opacity + ")";
--this.opacity;
}
this.onfinish = null;
/**
* Finishes fading and removes fading object from document tree
* @public
* @returns void
*/
this.finish = function() {
this.opacity = 10;
document.body.removeChild(faderObj);
clearInterval(interval);
if (this.onfinish) this.onfinish();
this.onfinish = null;
}
}
var Uploader = {uploaderForm: null,
upload: function(form) {
this.uploaderForm = form;
var frame = this.getIFrame();
form.target = frame.name;
form.submit();
form.target = "";
return false;
}, uploadCallBack: function(message, status, tmpFileId) {
var form = this.uploaderForm;
form.tmpFileId.value = tmpFileId;
var frame = this.getIFrame();
frame.src = "";
Loading.hide();
}, getIFrame: function() {
var iFrame = document.getElementById('_file_uploader');
if (iFrame == null) {
iFrame = document.createElement("iframe");
iFrame.name = "_file_uploader";
iFrame.id = "_file_uploader";
iFrame.src = "";
iFrame.target = "_self";
iFrame.style.width = "0px";
iFrame.style.height = "0px";
iFrame.style.border = "none";
document.body.appendChild(iFrame);
}
return iFrame;
}
};