Java Script and Ajax

by JustEtc Publications Ltd




Distributed by justEtc

What you really need to learn in Javascript?



What you really need to learn in Javascript? 
1. Where you can place JavaScript codes?
2. Some basic programming:
<script language="javascript" type="text/javascript">
</script>
<script language="javascript" type="text/javascript">
document.write('<b>Hello World</b>');
</script>
This will only be displayed in javascript enabled browsers.
<script language="javascript" type="text/javascript">
document.write('<a href="script.htm">Page Requiring Javascript</a>');
</script>
3. Variables and their scopes
<script language="javascript" type="text/javascript">
var hello = 'Hello World';
document.write(hello);
</script>
var mynum = 5;
var smokes = false;
var riches = null;
var today = new Date;
Example use of variables:
<script language="javascript" type="text/javascript">
var questions = '<p>If you have any questions about this
please <a href="mailto:me@myaddress.com">email me</a>.</p>';
document.write(questions);
</script>
Another block can refer to questions variables without reassigning the value
<script language="javascript" type="text/javascript">
document.write(questions);
</script>
variables declared within a function is recognized only withing that function. Variables declared outside of a function is recognized anywhere in the webpage within javascript code from the declaration place.
4. Operators
Assignment operators
<script language="javascript" type="text/javascript">
var rich = 5000;
var lotsOfMoney = 100000;
rich = lotsOfMoney;
document.write(rich);
</script>
Arithmetic and concatenation operators
five = two + three;
profit = income - expenses;
income = sales * price;
payment = total / instalments;
option = randnum % choices;
b = ++a;
c = a++;
d = --a;
e = a--;
Combination of Operators like c/c++
joy += happiness;
price -= discount;
capital *= interest;
pie /= slices;
options %= choice;
Example use:
<script language="javascript" type="text/javascript">
var singlePrice = 8;
var bulkPrice = singlePrice * 9;
document.write('<p>Buy our Widgets $'
+singlePrice+' for one, $'+bulkPrice+' for ten</p>');
</script>
5. Comparing Variables, Logical statements
<script language="javascript" type="text/javascript">
var red = 5;
var blue = 3;
var match = null;
if (red == blue)
{
match = 'equal';
}
else
{
match = 'unequal';
}
document.write(red + ' and ' + blue + ' are ' + match);
</script>
Other comparison operators:
if (red > blue)
if (red >= blue)
if (red < blue)
if (red <= blue)
if (red != blue)
Combining more than one comparison
if ((red == blue) || (red == green))
<script language="javascript" type="text/javascript">
var red = 5;
var blue = 3;
var green = 3;
var match = null;
if ((red == blue) && (red == green))
{
match = 'equal';
}
else
{
purple = 'unequal';
}
document.write(red + ' and ' + blue + ' are ' + match);
</script>
Comparison in short
red == blue ? match = 'equal' : match = 'unequal';
instead of
if (red == blue)
{
match = 'equal';
}
else
{
match = 'unequal';
}
Example Use:

<script language="javascript" type="text/javascript">
var discPrice = 25;
var regPrice = 25;
var discount = regPrice - discPrice;
if (discount > 0)
document.write('<p>Save $'+discount+ ' off the normal price of $' +regPrice+ 'now only $'+discPrice+'.</p>');
else
document.write('<p>Buy now at our regular cheap price of $' + regPrice+'.</p>' );
</script>
6. Switch statement in Javascript, very similar to C/C++/Java
use switch instead of multiple if/else if
<script language="javascript" type="text/javascript">
var red = 1;
var result = null;
switch (red)
{
case 1: result = 'one'; break;
case 2: result = 'two'; break;
default: result = 'unknown';
}
document.write(result);
</script>
Example:
<script language="javascript" type="text/javascript">
var message = 0;
switch (message)
{
case 1: document.write('Merry Christmas'); break;
case 2: document.write('Happy New Year'); break;
case 3: document.write('Happy Easter'); break;
case 4: document.write('Happy Holidays'); break;
default: document.write('Welcome');
}
</script>
7. Function
Defining a function
function myCode()
{
document.write('<b>Hello World</b>');
}
calling a function
myCode()
Example:
function displayMessage()
{
switch (message)
{
case 1: document.write('Merry Christmas'); break;
case 2: document.write('Happy New Year'); break;
case 3: document.write('Happy Easter'); break;
case 4: document.write('Happy Holidays'); break;
default: document.write('Welcome');
}
}
var message = 0;
displayMessage();
parameter passing
function writeSentence(argument1,argument2)
{
document.write('The '+argument1+' is '+argument2+'.<br />');
}
var a = 'table';
var b = 'chair';
var c = 'red';
var d = 'blue';
writeSentence(a,c);
writeSentence(b,c);
b = 'other ' + b;
writeSentence(b,d);
writeSentence('table',b); //passing the value directly
Example:
function displayMessage(m)
{
switch (m)
{
case 1: document.write('Merry Christmas'); break;
case 2: document.write('Happy New Year'); break;
case 3: document.write('Happy Easter'); break;
case 4: document.write('Happy Holidays'); break;
default: document.write('Welcome');
}
}
In Javascript functions can also return values
function validField(fld)
{
if (fld == '') return false;
return true;
}
function validField(fld)
{
return (fld != '');
}
How to receive returned values and process
document.write(myField + ' is ');
if (!validField(myField))
{
document.write('not ');
}
document.write('empty');
8. Alert and confirm
alert('Alert Message');
Will display a message box with the message. Very useful in debugging javascript applications.
use confirm(), when you need user agreement on an issue. like:
if (confirm('Select a button'))
{
alert('You selected OK');
}
else
{
alert('You selected Cancel');
}
9. comments
// Scrolling Ad Javascript
// copyright 3rd September 2004, by Stephen Chapman
// permission to use this Javascript on your web page is
// granted provided that all of the code in this script (including
// these comments) is used without any alteration
or
/* Scrolling Ad Javascript
copyright 3rd September 2004, by Stephen Chapman
permission to use this Javascript on your web page is
granted provided that all of the code in this script (including
these comments) is used without any alteration */

10. Debugging JavaScript
Test in different browsers like IE, Mozilla, Firfox, Netscape
Enable Javascript and script debugging
Script debugging usually reside under tools menu under browsing or web development sub-options

Using alert to check variable values or if you can reach to a particular point of your code
use bookmarklets, these are small scripts that can be used as plug in into browsers to provide error information.
Use firebug in firefox, also use error console under tools menu to debug javascript error.
Visual interdev provides Javascript debugging you may also enable external debugging by such programs
11. External javascript

You can place all of your javascript codes to an external file. and use the file scripts/functions from any webpage.
You just need to provide a reference to that external file.
You can provide reference as follows:
<script language="javascript" type="text/javascript"
src="hello.js">
</script>
Note: do not include any <script> or </script> in the external file.
12. Using <noscript> tag: this tag may help you to provide some information to the visitors
when javascript is disabled or not supported by the browsers.
<script language="javascript" type="text/javascript">
document.write('<b>Hello Javascript World</b>');
</script>
<noscript>Hello World Without Javascript</noscript>
<noscript>
This page uses Javascript. Your browser either
doesn't support Javascript or you have it turned off.
To see this page as it is meant to appear please use
a Javascript enabled browser.
</noscript>
13. Objects and properties in Javascript
var strlen = myField.length;
var str = mynum.toString();
function theLetter(num)
{
var str = 'abcdefghijklmnopqustuvwxyz';
return str.substr(num-1,1);
}
document.write(theLetter(5));
14. Arrays in Javascript
var myArray = new Array();
var myArray = new Array('message one',
'message two','message three');
document.write(myArray[0]);
myArray[3] = 'message four';
function displayMessage(m)
{
var greeting = new Array('Welcome','Merry Christmas',
'Happy New Year','Happy Easter','Happy Holidays');
if (m < 0 || m > greeting.length) m = 0;
document.write(greeting[m]);
}
15. Loops
for (var i=0; i<10; i++)
{
document.write(i);
}
var x = 0;
while (x<10)
{
document.write(x);
x++;
}
var x = 12;
do
{
document.write(x);
x++;
} while (x<10)
16. Date and Time in Javascript
//current date
var myDate = new Date;
myDate.setDate(15);
myDate.setMonth(3); // January = 0
myDate.setFullYear(2006);
myDate.setDate(myDate.getDate()+7);


How to implement multiple tab webpages in Ajax and Javascript



The following two examples will demonstrate how to use javascript and/or ajax to implement multiple tab webpages. http://www.dynamicdrive.com/dynamicindex17/ajaxtabscontent/

http://www.barelyfitz.com/projects/tabber/example2.html

I hope to be familiar with these concepts and use them in my work soon.

Handling Checkbox arrays with Javascript::GetElementsByName:XHTML supported



The following code demonstrates how to handle checkboxes with javascript. Note the names of all check boxes are same myInput[]. It could also be myInput. Both works as an array to contain the controls' values. I prefer myInput[] as you can handle this control in PHP as an array. If you use $arr=$_POST['myInput'], $arr will contain the values of the controls.

Note the use of getElementsByName(). It is easy to manipulate javascript controls using this name. You do not need to send a value/control to the function. And in many times, document.myform.control, does not work right, specially if you want to main XHTML standard[i need to check more on this]. getElementById is also very useful. You may use getElementById for most times, but with checkbox arrays getElementsByName is better choice.

Also, note that when a form is submitted only the values of the checked check boxes are submitted to the server. You may wish to use hidden controls to keep the values, so that all values are submitted and based on the checked/non-checked you can ..control your work

<html>
	<head>
		<script type="text/javascript">
			function getElements()
			  {
			  var x=document.getElementsByName("myInput[]");
			  alert(x.length);
			  alert(x[0].value);
			  alert(x[1].value);
			  alert(x[2].value);


			  }
		</script>
</head>

<body>
	<input name="myInput[]" type="checkbox" size="20" value='10'/>10 
<input name="myInput[]" type="checkbox" size="20" value='20' />20
<input name="myInput[]" type="checkbox" size="20" value='30' />30

Want to check how the code works, check below

10
20
30



Javascript by Example



Java Script by Example:

Please check the URL:

http://examples.oreilly.com/jscript2/

Javascript - Form validation



The code will be helpful in validating data entry forms such as: user registration, user creation. validate_required is used by all other functions

function validate_required(field,alerttxt)
	{
		with (field)
		{
			if (value==null||value=='')
			{
				alert(alerttxt);return false
			}
			else {return true}
		}
	}
	
	function validateTicketCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(type,'Type must be filled out!')==false)
			{type.focus();return false}
			
			if (validate_required(subject,'Subject must be filled out!')==false)
			{subject.focus();return false}
						
		}
	}

	function validate_customer_create_form(thisform)
	{
		with (thisform)
		{
			if (validate_required(firstName,'First name must be filled out!')==false)
			{firstName.focus();return false}
			
			if (validate_required(lastName,'Last name must be filled out!')==false)
			{lastName.focus();return false}
			
			if (validate_required(phone,'Phone must be filled out!')==false)
			{phone.focus();return false}
			
		}
	}
	
	
	function validateUserCreateForm(thisform)
	{
		with (thisform)
		{
						
			if (validate_required(firstName,'First name must be filled out!')==false)
			{firstName.focus();return false}
			
			if (validate_required(lastName,'Last name must be filled out!')==false)
			{lastName.focus();return false}
			
			if (validate_required(shortName,'Short name must be filled out!')==false)
			{shortName.focus();return false}
			
			if (validate_required(username,'Username must be filled out!')==false)
			{username.focus();return false}
			
			
			if (validate_required(password,'Password must be filled out!')==false)
			{password.focus();return false}
			
			if (password.value.length < passwordLength.value) {alert("Password must be at least "+ passwordLength.value +" char long");	password.focus();return false}
			
			if (validate_required(password2,'Please re-enter password!')==false)
			{password2.focus();return false}
			
			if (password.value != password2.value)
			{
				alert("Password did not match");
				password2.focus();
				return false			
			}
			
			
		}
	}



JavaScript - Miscellaneous Validations



	function validateDomainName(strValue) 
	{
		return /www\.[a-z0-9_\-]+\.[a-z]{2, 3}/ig.test(strValue);		
	}

	function validateDomainName(strValue) 
	{
		return /www\.[a-z0-9_\-]+\.[a-z]{2, 3}/ig.test(strValue);		
	}


	//not 100% right, will fix later
	function checkDateFormat()
	{
		var pattern = new RegExp(0|1[0-9]/[0-3][0-9]/[0-9][0-9]);
		if(document.getElementById('timestampStarted').value.match(pattern))
		{
			var date_array = document.getElementById('timestampStarted').value.split('/');
			
			var month = date_array[0];
			var day = date_array[1];
			var year = date_array[2];

			// This instruction will create a date object
			source_date = new Date(year,month,day);
	
			if(month != source_date.getMonth())
			{
				alert('Month is not valid!');
				return false;
			}
	
			if(day != source_date.getDate())
			{
				alert('Day is not valid!');
				return false;
			}
			
			if(year != source_date.getYear())
			{
				alert('Year is not valid!');
				return false;
			}
		}
		else
		{
			alert('Date format is not valid!');
			return false;
		}
	
		return true;
	}



	function validateEmail( strValue) 
	{
		var objRegExp  = /(^[a-z]([a-z_\.]*)@([a-z_\.]*)([.][a-z]{3})$)|(^[a-z]([a-z_\.]*)@([a-z_\.]*)(\.[a-z]{3})(\.[a-z]{2})*$)/i;

  		//check for valid email
  		return objRegExp.test(strValue);
	}


//AJAX Example
function ajaxFunctionGeneral()
	{
		var page_request = false

		if (window.XMLHttpRequest) // if Mozilla, IE7, Safari etc
			page_request = new XMLHttpRequest()
		else if (window.ActiveXObject)
		{ // if IE
			try 
			{
				page_request = new ActiveXObject("Msxml2.XMLHTTP")
			} 
			catch (e)
			{
				try
				{
					page_request = new ActiveXObject("Microsoft.XMLHTTP")
				}
				catch (e)
				{
				}
			}
		}
		else		
			return false
		return page_request;
	}

	function reboot(deviceId)
	{
		var response=confirm('Are you sure to reboot');
		
		if(!response)
			exit;
		
		page_request = ajaxFunctionGeneral();
		if (!page_request) return false;
		
		page_request.onreadystatechange=function()
      {
      	if(page_request.readyState==4)
        	{
        		var response=page_request.responseText;
        		var displayArea = document.getElementById('showDiagnosticsResults');
        		displayArea.value = response;
        	}
      }
		page_request.open('GET', '/Inventory/Diagnostics/reboot.php?deviceId='+deviceId, true)
		page_request.send(null)
	}



Javascript Codes



Javascript is a very powerfull scripting language for web-site development. Also, it is in much demand. In Europe Javascript experts earn 29-58 pound/hour [ref: Internet]

	var serviceInstancesArrAtLoad = Array();
	var serviceInstancesArrAtSubmit = Array();
	var tempArr=Array();	
	
	function validate_required(field,alerttxt)
	{
		with (field)
		{
			if (value==null||value=='')
			{
				alert(alerttxt);return false
			}
			else {return true}
		}
	}
	
	function validateTicketCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(type,'Type must be filled out!')==false)
			{type.focus();return false}
			
			if (validate_required(subject,'Subject must be filled out!')==false)
			{subject.focus();return false}
						
		}
	}

	function validate_customer_create_form(thisform)
	{
		with (thisform)
		{
			if (validate_required(firstName,'First name must be filled out!')==false)
			{firstName.focus();return false}
			
			if (validate_required(lastName,'Last name must be filled out!')==false)
			{lastName.focus();return false}
			
			if (validate_required(phone,'Phone must be filled out!')==false)
			{phone.focus();return false}
			
		}
	}
	
	
	function validateUserCreateForm(thisform)
	{
		with (thisform)
		{
						
			if (validate_required(firstName,'First name must be filled out!')==false)
			{firstName.focus();return false}
			
			if (validate_required(lastName,'Last name must be filled out!')==false)
			{lastName.focus();return false}
			
			if (validate_required(shortName,'Short name must be filled out!')==false)
			{shortName.focus();return false}
			
			if (validate_required(username,'Username must be filled out!')==false)
			{username.focus();return false}
			
			/*
			if (validate_required(password,'Password must be filled out!')==false)
			{password.focus();return false}
			
			if (password.value.length < passwordLength.value) {alert("Password must be at least "+ passwordLength.value +" char long");	password.focus();return false}
			
			if (validate_required(password2,'Please re-enter password!')==false)
			{password2.focus();return false}
			
			if (password.value != password2.value)
			{
				alert("Password did not match");
				password2.focus();
				return false			
			}
			*/
			
		}
	}

	function validate_assign_group_form(thisform)
	{
		with (thisform)
		{
			if (validate_required(groupId,'Group name must be filled out!')==false)
			{groupId.focus();return false}
			
			if (validate_required(userId,'Action on invalid user!')==false)
			{userId.focus();return false}		
		}
	}
	
	function validateGroupCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(name,'Group name must be filled out!')==false)
			{name.focus();return false}
			
		}
	}
	
	function validateAssignGroupPermissionForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(taskId,'Task module name must be filled out!')==false)
			{taskId.focus();return false}
			
		}
	}
	
	function validateAssignTaskPermissionForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(groupId,'Group name must be filled out!')==false)
			{groupId.focus();return false}
			
		}
	}
	
	function validateUserEditForm(thisform)
	{
		with (thisform)
		{
						
			if (validate_required(firstName,'First name must be filled out!')==false)
			{firstName.focus();return false}
			
			if (validate_required(lastName,'Last name must be filled out!')==false)
			{lastName.focus();return false}
			
			if (validate_required(shortName,'Short name must be filled out!')==false)
			{shortName.focus();return false}
			
			if (validate_required(username,'Login id must be filled out!')==false)
			{username.focus();return false}
						
			if (password.value.length>0)
			{
				if (password.value.length < passwordLength.value) {alert("Password must be at least "+ passwordLength.value +" char long");	password.focus();return false}
				
				if (validate_required(password2,'Please re-enter password!')==false)
				{password2.focus();return false}
			}
			
			if (password.value != password2.value)
			{
				alert("Password did not match");
				password2.focus();
				return false
			}
			
		}
	}
	
	function validateInventoryCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(serial,'serial must be filled out!')==false)
			{serial.focus();return false}
			
			if (validate_required(hardwareAddress,'Hardware Address must be filled out!')==false)
			{hardwareAddress.focus();return false}
		}
	}
	
	function validateInventoryTypeCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(name,'Name must be filled out!')==false)
			{name.focus();return false}
		}
	}
	
	function validateInventoryModelCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(name,'Name must be filled out!')==false)
			{name.focus();return false}
			
			if (validate_required(manufacturerId,'Manufacturer must be filled out!')==false)
			{manufacturerId.focus();return false}
			
			if (validate_required(typeId,'Type must be filled out!')==false)
			{typeId.focus();return false}
			
			
		}
	}
	
	function validateInventoryManufacturerCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(name,'Name must be filled out!')==false)
			{name.focus();return false}
		}
	}
	
	
	function validateServiceCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(name,'Name must be filled out!')==false)
			{name.focus();return false}
			
			if (validate_required(typeId,'Type must be filled out!')==false)
			{typeId.focus();return false}
			
			
		}
	}
	
	function validateHostingCreateForm(thisform)
		{
			with (thisform)
			{
				if (validate_required(serviceId,'Service must be filled out!')==false)
				{serviceId.focus();return false}
				
				if (validate_required(storageSpace,'Storage space must be filled out!')==false)
				{storageSpace.focus();return false}
			}
		}
		
	function validateDomainName(strValue) 
	{
		return /www\.[a-z0-9_\-]+\.[a-z]{2, 3}/ig.test(strValue);
		
		//var objRegExp  = /^\w+([\.-]?\w+)*(\.\w{2,3})/;

  		//check for valid domain
  		//return objRegExp.test(strValue);
	}
	
	function validateDomainServiceCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(name,'Domain name must be filled out!')==false)
			{name.focus();return false}
			
			/*if (validateDomainName(name.value)==false)
			{alert('Please enter valid domain name');name.focus();return false;}*/
			
			if (validate_required(registrar,'Registrar must be filled out!')==false)
			{registrar.focus();return false}
			
			if (validate_required(registrationTimestamp,'Registration timestamp must be filled out!')==false)
			{registrationTimestamp.focus();return false}
			
			if (validate_required(expiryTimestamp,'Expiry timestamp must be filled out!')==false)
			{expiryTimestamp.focus();return false}
			
			if (validate_required(username,'User name must be filled out!')==false)
			{username.focus();return false}
			
			if (validate_required(password,'Password must be filled out!')==false)
			{password.focus();return false}
			
			if (password.value.length < passwordMinLength.value || password.value.length>passwordMaxLength.value)
			{alert('Password must be '+ passwordMinLength.value+ '-'+ passwordMaxLength.value +' chars long');password.focus();return false;}
			
			if (password.value != password2.value)
			{alert('Password must match');password2.focus();return false;}
		}
	}
	
	
	
	
	function validateCommunityCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(name,'Name must be filled out!')==false)
			{name.focus();return false}
		}
	}
	
	function validatePostalCodeCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(postalCode,'Postal code must be filled out!')==false)
			{postalCode.focus();return false}
			
			if (validate_required(communityId,'Community must be filled out!')==false)
			{communityId.focus();return false}
		}
	}
	
	function validateStreetTypeCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(name,'Name must be filled out!')==false)
			{name.focus();return false}
		}
	}
	
	function validateStreetCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(name,'Name must be filled out!')==false)
			{name.focus();return false}
			
			if (validate_required(typeId,'Type must be filled out!')==false)
			{typeId.focus();return false}
			
			if (validate_required(communityId,'Community must be filled out!')==false)
			{communityId.focus();return false}
		}
	}
	
	function validateUnitCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(streetId,'Street must be filled out!')==false)
			{streetId.focus();return false}
			
			if (validate_required(communityId,'Community must be filled out!')==false)
			{communityId.focus();return false}
			
			if (validate_required(number,'Number must be filled out!')==false)
			{number.focus();return false}
			
			if (validate_required(nodeId,'Node must be filled out!')==false)
			{nodeId.focus();return false}
			
		}
	}
	
	function validatePlantCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(name,'Name must be filled out!')==false)
			{name.focus();return false}
		}
	}
	
	function validateCreateTicketCategoryForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(name,'Name must be filled out!')==false)
			{name.focus();return false}
		}
	}
	
	
	function validateStartWorkOnTicketForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(startTimestamp,'Start Timestamp must be filled out!')==false)
			{startTimestamp.focus();return false}
		}
	}
	
	function validateTicketReportForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(date,'Date must be filled out!')==false)
			{date.focus();return false}
		}
	}
	
	
	function validateCloseTicketForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(date,'Date must be filled out!')==false)
			{date.focus();return false}
			
			if (validate_required(time,'Time must be filled out!')==false)
			{time.focus();return false}
			
		}
	}

	function validateCreateWorkOrder(thisform)
	{
		with (thisform)
		{
			if (validate_required(inventoryId,'Inventory must be filled out!')==false)
			{inventoryId.focus();return false}
			
			if (validate_required(assignedTo,'Assigned to must be provided!')==false)
			{assignedTo.focus();return false}
			
			if (validate_required(scheduledDate,'Scheduled date must be provided!')==false)
			{scheduledDate.focus();return false}
			
			if (validate_required(scheduledTime,'Scheduled time must be provided!')==false)
			{scheduledTime.focus();return false}
			
		}
	}
	
	
	
	
	function addService(services,serviceId)
	{
		for (var i = 0; i < services.length; i++) 
		{
			if (services.options[i].selected) 
			{
				serviceIdLength = serviceId.length++;
				serviceId.options[serviceIdLength].text = services.options[i].text;
				serviceId.options[serviceIdLength].value = services.options[i].value;
				
			}
		}
	}
	
	
	function removeService(serviceId)
	{
		for (var i = 0; i < serviceId.length; i++) 
		{
			if (serviceId.options[i].selected) 
			{
				
				serviceId.options[i].text = '';
				serviceId.options[i].value = '';
				serviceId.options[i].selected = false;
				serviceId.options[i].remove();
			}
			
		}
		
	}
	
	function validateAssignInventoryForm()
	{
		
		var serviceArr=document.getElementsByName("serviceArr[]");
		length=serviceArr.length;
		isAnySelected = false;
		
		for (var i=0;i 0)
			   isServiceRequested = 1;
			   
			if (serviceArr[i].checked == true)
			{
			   if (inventoriesHavingSameService[service] >= 0)
			   	inventoriesHavingSameService[service]=inventoriesHavingSameService[service]+1;
			   else 
			   	inventoriesHavingSameService[service]=1;
			   
			   if (servicesHavingSameInventory[inventory] > 0)
			   	servicesHavingSameInventory[inventory]=servicesHavingSameInventory[inventory]+1;
			   else
			   	servicesHavingSameInventory[inventory]=1;
			}
			
			
		}	
		if (   (!isAnySelected) && (isServiceRequested) )
		{
			alert('Service & inventory requested. But no checkbox is selected');
			return false;
		}
		else if (!isAnySelected)
		{
			var response = confirm('No checkbox is selected, do you want to proceed');
			if (!response) return false;
		}
		
		var errMsg ='';
		
		for (k=1;k= 0 )
			{	
				if ( (serviceRequested[k] != inventoriesHavingSameService[k])  )
				{
					if (serviceRequested[k]>0) 
						errMsg = errMsg + "Inventory is not checked properly for service " + k +", Requested:" + serviceRequested[k] +", Assigned:" + inventoriesHavingSameService[k] + "\n";
					else if (serviceRequested[k]==0 && inventoriesHavingSameService[k]>0)
						errMsg = errMsg + "Inventory is not checked properly for service " + k +", Requested:" + serviceRequested[k] +", Assigned:" + inventoriesHavingSameService[k] + "\n";
				}
			}
		}
			
		if (errMsg.length>0)
		{
			alert(errMsg);
			return false;
		}
		return true;
	}
	
	//not 100% right, will fix later
	function checkDateFormat()
	{
		var pattern = new RegExp(0|1[0-9]/[0-3][0-9]/[0-9][0-9]);
		if(document.getElementById('timestampStarted').value.match(pattern))
		{
			var date_array = document.getElementById('timestampStarted').value.split('/');
			
			var month = date_array[0];
			var day = date_array[1];
			var year = date_array[2];

			// This instruction will create a date object
			source_date = new Date(year,month,day);
	
			if(month != source_date.getMonth())
			{
				alert('Month is not valid!');
				return false;
			}
	
			if(day != source_date.getDate())
			{
				alert('Day is not valid!');
				return false;
			}
			
			if(year != source_date.getYear())
			{
				alert('Year is not valid!');
				return false;
			}
		}
		else
		{
			alert('Date format is not valid!');
			return false;
		}
	
		return true;
	}

	//used by assignService.php
	function initializeServiceInstanceArr()
	{
		if (serviceInstancesArrAtLoad.length == 0)
			serviceInstancesArrAtLoad=document.getElementsByName("serviceInstances[]");
		length=serviceInstancesArrAtLoad.length;

		for(i=0;i0 )
			{
				var forwardAddresses = forwardAddress.value.split(',');
				var length=forwardAddresses.length;
				for(var i=0;i=1)
				{
					lengthModelId=modelId.options.length;
					modelId.options[lengthModelId-1]=null;
				}
      
        		for(var i=0;i=1)
				{
					lengthAddressId=addressId.options.length;
					addressId.options[lengthAddressId-1]=null;
				}
      
        		for(var i=0;i=1)
				{
					lengthServiceId=serviceId.options.length;
					serviceId.options[lengthServiceId-1]=null;
				}
      
        		for(var i=0;i passwordMaxLength.value)
			{alert('Password length should be <= '+passwordMaxLength.value );password.focus();return false}
			
						
			if (validate_required(password2,'Please re-enter site password !')==false)
			{password2.focus();return false}
			
			if (password.value != password2.value)
			{
				alert("Site User Passwords must match");
				password2.focus();
				return false
			}
		}
	}
	
	function validateHostingDomainUserCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(domainId,'Domain name must be filled out!')==false)
			{domainId.focus();return false}
			
			
			if (validate_required(username,'Domain user name must be filled out!')==false)
			{username.focus();return false}
			
			if (validate_required(password,'Domain password must be filled out!')==false)
			{password.focus();return false}
						
			if ( password.value.length  < passwordMinLength.value )
			{ alert('Password length should be at least '+passwordMinLength.value); password.focus();return false }
			
			if (password.value.length  > passwordMaxLength.value)
			{alert('Password length should be <= '+passwordMaxLength.value );password.focus();return false}
			
			
			if (validate_required(password2,'Please re-enter site password !')==false)
			{password2.focus();return false}
			
			if (password.value != password2.value)
			{
				alert("Domain User Passwords must match");
				password2.focus();
				return false
			}
		}
	}
	
	
	//outage
	function validateOutageCreateForm(thisform)
	{
		with (thisform)
		{
			if (validate_required(subject,'Subject must be filled out!')==false)
			{subject.focus();return false}
			
			//check community selection
			var communityNamesArr=document.getElementsByName("communityNames[]");
			lengthArr= communityNamesArr.length;			
			var isAnySelected = false;
			
			for (var i=0;i



Introduction to JQuery





JavaScript DOM: Must knowledge to understand Ajax



  • Understanding Javascript DOM is the first step to understand Ajax.
  • DOM provides many methods to access and edit individual components of a web-page/document. The methods are called getters.
  •  < div id = 'test' > Hello < /div >
    getElementById method can reference to this div element. var testDiv = document.getElementById("test"); CSS #test{} refers to the same area of the document
  • getElementsByTagName: all the elements with the partcular tag name. Returns an array. var testTag = document.getElementsByTagName("p"); just like p{} in CSS applies to all

    tags.

  • testTag.length can be useful.
  • You can also cycle through the elements and take some actions
          for(var i = 0; i < testTag.length ; i++){
             //do something
          }
       
  • Another example: document.getElementById("test").getElementsByTagName("p"); [CSS #test p{} - will affect the same area in CSS]
  • DOM provides getAttribute () : can access the value of an attribute. < p id='test' title='justEtc Computer' > Hello <p> : var title= document.getElementById("test").getAttribute("title");
  • Web-page can be thought of a set of interconected nodes. getElementById, getElementsByTagName, getAttribute - all help in accessing the nodes.
  • Three basic types of nodes in web-pages: element, text, attribute. element - building block, text = attribute = content
  • Every node is contained under another node. So there will be parent and child relationships. parentNode, childNode - are corresponding methods for accessing parents and childs.
  • Example: var test = document.getElementById("test"); var testParent= test.parentNode; var testChild = test.childNodes;
  • childNodes - returns an array
  • var allEle = document.getElementsByTagName("*"); - a collection of all the elements of the web-page.
  • firstChild - first Child of an element, lastChild - lastChild of an element, previousSibling, nextSibling - having same parent of the current node (next element), nodeValue, nodeValue - content of a node,
  • DOM Setters
  • Using DOM, you can create elements dynamically and put it in the document. createElement() - method serves the purpose
  • var paragraph = document.createElement("p"); - element created - element node - but not inserted in the document yet
    
    var textNode = document.createTextNode("A new text node from DOM!"); - creates a text node
    
  • setAttribute() - method can be used to set the attributes of a node. example: paragraph.setAttribute("title", "introduction");
  • appendChild() - append one node under another node;
  •     var pNode = document.createElement("p");
        var textNode = document.createTextElement("How is it going?");
         pNode.setAttribute("title","Test Title");
         pNode.appendChild(textNode);     
         var testDiv = document.getElementById("testDiv");
         testDiv.appendChild(pNode);
    
  • removeChild() - helps to remove a child node from a parent node



Ajax: An Overview



  • Ajax: dynamically changes a portion of the current web-page without refreshing the total web-page. Resembles the way IFrame works. So far I know, google uses IFrame to display/refresh maps in web-pages
  • XMLHttpRequest is the object that serves the purpose of Ajax
  • The way it works: create an instance of the XMLHttpRequest object, send request to the back-end web-page that will do some processing and perhaps return some data, receive the response data, dynamically change the content of the target area, you may need to get a reference to the target area using DOM, after sending request - you have to wait for the response to come back
  • create an instance of the XMLHttpRequest object: It varies for the different browsers. IE provides ActiveX Control for the purpose. A sample code can be as follows:
  • 
      function getAjaxObject(){
        var ajaxObject = false;
        if (window.XMLHttpRequest){
             ajaxObject = new XMLHttpRequest();
        }else if (window.ActiveXObject) {
          try{
            ajaxObject = new ActiveXObject("Msxml2.XMLHTTP");
          }catch(e){
             try{
              ajaxObject = new ActiveXObject("Microsoft.XMLHTTP");
             }catch(e){
               ajaxObject = false;
             }
    
          }
        }
        return ajaxObject; 
      }
    
    
  • XMLHttpRequest has three core components. onreadystatechange - event to notify response has come or identify server activity, open - method , send method
  • use of onreadystatechange
    if (ajaxObject){
       ajaxObject.onreadystatechange = takeAction; //takeAction - reference to a function
    }
    
  • Open method specifies the server side script to handle the request, data to send to the server, method of sending (GET, POST) : Required: type of request (first argument), location of the file in the server (2nd argument)
  • Open method: third argument: true = processing will be done asynchronously, false = synchronous processing - browser will stop processing until response comes [true is usually better]
  • send : send method initiates the request : also passes data to the server
  • For GET method the argument can be set to null, for POSt method the argument can be a query string such as "id=500&name=keith&age=18"
  • use setRequestHeader() - to provide metadata
  • Sample code:
     var ajaxObject = getAjaxObject();
     if (ajaxObject ){
        ajaxObject.onreadystatechange = takeAction; 
        ajaxObject.open("POST","file.jsp", true);
        ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        ajaxObject.send("id=500&name=keith&age=18");
     }
    
  • How to receive and process the response:
  • The readyState property indicates the current status of the request. 0 - Uninitialized, 1 - Loading, 2 - Loaded, 3 - interactive, 4 - complete
  • each time the value of readyState changes onreadystatechange - event is triggered. At value 4, we can collect the response and change the web-page dynamically
  • Sample:
     function takeAction(ajaxObject){
      if (ajaxObject.readyState == 4) {
         //do something with the response
      }
     }
    
  • status is another property to consider - it indicates the status of sending request like 404 - not found, 200 = success, 304 = not modified
  • The prev function
     function takeAction(ajaxObject){
      if (ajaxObject.readyState == 4) {
         if (ajaxObject.status == 200 || ajaxObject.status == 304){ //response was sent succesfully 
              //do something with the response
         }
      }
     }
    
  • responseText is the response from the server
  •  function takeAction(ajaxObject){
      if (ajaxObject.readyState == 4) {
         if (ajaxObject.status == 200 || ajaxObject.status == 304){ //response was sent succesfully 
              //do something with the response
              alert(ajaxObject.responseText);
         }
      }
     }
    
  • responseXML can be used when the response was sent as xml and the response header is "text/xml"
  • All together
      function getAjaxObject(){
        var ajaxObject = false;
        if (window.XMLHttpRequest){
             ajaxObject = new XMLHttpRequest();
        }else if (window.ActiveXObject) {
          try{
            ajaxObject = new ActiveXObject("Msxml2.XMLHTTP");
          }catch(e){
             try{
              ajaxObject = new ActiveXObject("Microsoft.XMLHTTP");
             }catch(e){
               ajaxObject = false;
             }
    
          }
        }
        return ajaxObject; 
      }
    
      function entryPoint(){
        var ajaxObject = getAjaxObject();
         if (ajaxObject ){
        ajaxObject.onreadystatechange = function(){
          takeAction(ajaxObject); 
        };
        ajaxObject.open("POST","file.jsp", true);
        ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        ajaxObject.send("id=500&name=keith&age=18");
     }
     }
     function takeAction(ajaxObject){
      if (ajaxObject.readyState == 4) {
         if (ajaxObject.status == 200 || ajaxObject.status == 304){ //response was sent succesfully 
              //do something with the response
              alert(ajaxObject.responseText);
              var testDiv = document.getElementById("test");
              testDiv.innerText = ajaxObject.responseText; 
         }
      }
     }
    
  • Processing Response Data
  • The usual practice: response data can be in one of three formats: XML, JSON, HTML. And may be plain text.
  • XML is the most common. example receive: var data = ajaxObject.responseXML; Here we can use the DOM functions to parse the XML data
  • Example:
    var data = ajaxObject.responseXML;
    data.getElementsByTagName("name")
    data.getElementsByTagName("name")[0]
    data.getElementsByTagName("name")[0].firstChild
    data.getElementsByTagName("name")[0].firstChild.nodeValue
    Similarly, you can use other DOM functions
    
  • To change the contents of the web-page dynamically, you can use the DOM methods like -- create, set, innerText, innerHtml (use carefully) methods. Check the JavaScript DOM article [846] in this web-site. adding and removing childs/elements may be required in some situations - DOM also supports that
  • You can also send data as JSON from the server side like: JSON format:
    {"person":{ "name":"Keith Tang", "school":"uofm" } }
  • Receiving and extracting information from JSON: [content type will be text]
     var data = eval('('+ ajaxObject.responseText +')');
     var name = data.person.name;
     var school = data.person.school; 
    
  • Response data as HTML
  • The response can come as HTML. This may be useful, if only one area of the web-page is affected and we want to put the HTML response in that area. Otherwise it may not be great. Also, we need to use innerHTML method that was introduced by IE and later adopted by others. Still, it's not a standard (W3C)
  • Example: The content type of response data should be text/html
           if (ajaxObject.status == 200 || ajaxObject.status == 304){ //response was sent succesfully 
              //do something with the response
              alert(ajaxObject.responseText);
              var testDiv = document.getElementById("test");
              testDiv.innerHTML = ajaxObject.responseText; 
         }