Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Fast Redirect Method

Page redirection is used to redirect/forward a page visitor to another page, such as when a pageor

* JavaScript Redirect - preferred method
* Timed Redirect with JavaScript
* meta-tag - provided for reference but not the preferred method.

Hands on experiences show following method is the fast, if that is what you want:

‹script language="JavaScript"›
; window.onload = function()
{ ; window.location.replace("http://yourdomain.com/")
}
‹/script›


http://grizzlyweb.com/webmaster/javascripts/redirection.asp#version2

Object Oriented Programming in JavaScript

There are several ways to do this, such as using prototype and JavaScript object. However, simplest may be the best. Following method matches the orthodox structure of OO, which is put everything inside of a class file:

; var ObjectClass = function(inputPara)
{
; var privateAttribute_1 = inputPara
; this.publicAttribute_Temp = 200
; function privateMethod_SetInternally()
{ ; privateAttribute_1 = 100
}
; this.publicMethod_1 = function()
{ ; privateMethod_SetInternally()
; return 50*privateAttribute_1
}
; this.publicMethod_Get = function()
{ ; return privateAttribute_1
}
; this.publicMethod_SetExternally = function(valueSetLater)
{ ; privateAttribute_1 = this.publicMethod_1*valueSetLater*123456789
}
}

Please note, for private method, do not use Varibalized Function, which is also called Function Literal, Function Reference or Function Pointer, like this:

; var privateMethod_SetInternally = function () {…}

Indeed, private method privateMethod_SetInternally is useless here, because you can always set internally directly:

; privateAttribute_1 = newValue

The purpose of privateMethod_SetInternally here is to show how to call this method, as stated in publistMethod_1. There is no way for outsider to use this private method, but through publistMethod_1.

All attributes/method started with this. is the public accessible by outsider caller, or the object based on this Class.

To use this Class, an object needs to be created:

; var obj = New ObjectClass(300)
; var att1_inThere = obj.publicMethod_Get()
; obj.publicMethod_SetExternally(400)

Please note, internally, calling all public accessible attributes/methods would not need with (), while private methods need to include (). However, for outsider object, public methods need to include () as well, like above.

There is a problem. Since internally calling public methods could not be with (), there is no way to pass the parameter while calling. In here, publicMethod_SetExternally can be called and assigned with parameters externally with no problem, but can only be called without assigning parameter internally. In this case, parameter is essential, so it would generate “not defined” error.

To overcome this, publicMethod_SetExternally needs to be rewritten as follows:

; this.publicMethod_SetExternally = function()
{ ; privateAttribute_1 = this.publicMethod_1*this.publicAttribute_Temp*123456789
}

Internally, it can now be called directly:

; this.publicMethod_SetExternally

Externally, it would be called like this:

; obj.publicAttribute_Temp = 400
; obj.publicMethod_SetExternally()

Javascript Error Message: is not a function

This error message appears when you use Varibalized Function (or called Function Literal, Function Reference, Function Pointer) method to declare function while you did not put into right order:

(Caller here)
; var func = function()
{
...
}

Solution 1:

; var func
(Caller here)
; func = function()
{
...
}

Solution 2:

(Caller here)
; function func()
{
...
}


http://www.dustindiaz.com/javascript-function-declaration-ambiguity/
Function Declaration in JavaScript

Tutorial: JavaScript:Defining Array

Array in JavaScript is class derived from Object. There are several ways of defining an array:

1. Regular array. Pass an optional integer argument to control array's size. However, if it is defined, no more element can be defined exceeding this number.
; var myfriends = new Array(optionalElementNumber)
; myfriends[0] = "John"
; myfriends[1] = "Bob"
; myfriends[2] = "Sue"

2. Condensed array:
; var myfriends = new Array("John", "Bob", "Sue")

3. Literal array:
; var myfriends = ["John", "Bob", "Sue"]

4. Empty array:
; var myArray = []
; myArray.push("John")
; myArray.push("Bob")
; myArray.push("Sue")

The elements/values of an array can be numeric, string, another array and object, or reference points to these:
; var var_0 = "John"
; var var_1 = "Bob"
; var var_2 = "Sue"
; var myfriends = new Array(var_0, var_1, var_2)
or
; var myfriends = [var_0, var_1, var_2]

When an element is another array, it becomes multidimensional array.

Stop Using for…in Loop Statement to Iterate Array In JavaScript

for…in loop statement is working fine. The problem is it does not work with Prototype. So standard loop statement is encouraged:

; for (var index=0; index { ; var item = myArray[index]
// Your code working on item here...
}

In addition, if the array is so large, each time to check the length will be so costly. Use following statement instead:

; for (var index=0, len=myArray.length; index { ; var item = myArray[index]
// Your code working on item here...
}


http://www.prototypejs.org/api/array

Get Selected Item in JavaScript Form

Somehow JavaScript mixed objects with attributes. For instance:

document.formName.listBoxName[i].selected

formName and listBoxName are references to two bojects. It might be good, but it just crosses the boundary of reference to object and the attributes. Don't know if this the the reason, to get selected item's value in form seems not easy. Google search shows there are so many people ask the question and not get right answers. Here is the easier way:

; function getValueOfSelectedItem(obj)
{ ; var val = obj.options[obj.selectedIndex].value
; if (val) (use val here)
}

To call this function, put the caller on onchange in HTML codes:

onChange="getValueOfSelectedItem(this)"

The beauty of it is there is no mixture of reference and attribute and you can pass anything of it without worry of crossing boundary issue.


http://www.java2s.com/Code/JavaScriptReference/Javascript-Properties/selectedIndexExample.htm

Can JavaScript Codes Be Added To SSRS Report?

The SQL Server Reporting Services HTML is poorly constructed so that the tags you'd most want to customize don't have Id's or Classes assigned. In addition, the ASPX pages just reference compiled assemblies, so the only real way to modify them is via CSS. Someone tried to edit the ReportingServices.js file, but it is neither the concept of customization nor standard functionality.

Conclusion: you could not add JavaScript block onto SSRS.



http://geekswithblogs.net/mnf/archive/2007/11/25/sql-server-reporting-services-notes.aspx
http://geekswithblogs.net/mnf/archive/2007/11/25/sql-server-reporting-services-notes.aspx
http://stackoverflow.com/questions/789303/is-it-possible-to-embed-javascript-into-an-ssrs-report

Parentheses () Outsider And After A Function - Nested Object Namespacing

It looks like:

; (function()
{ ...
})()

There are three purposes of it:

1. The function is anonymous so it can't be called the usual way. The outer brackets have to be there so that it can be called using brackets to enable the parameter feeding:

; (function(str){alert(str)}("test"))

2. Someone may to extend above-mentioned purpose to make the calling this anonymous function immediately after after the function definition, which is ofter called Self-ting Temporary Function. In this case, it is often with empty parameter.

3. Let us look at following example first:

; var myApp = {}
; myApp.message = 'hello'
; myApp.sayHello = function()
{ alert(this.message);
}
; myApp.sayHello() // works because "this" refers to myApp object.
; var importedfn = myApp.sayHello
; importedfn() // error because "this" refers to global object.

The lesson to be learned here is that this should never refer to an object being used as a namespace because it leads to confusion about importing identifiers from that namespace. People use nested object namespacing to avoid the identifier collisions. According to Peter Michaux, it is unnecessarily complex when the goal is simply avoiding identifier collisions.

Conclusion: Avoid this practice if you have other choice.


http://peter.michaux.ca/articles/javascript-namespacing
http://ejohn.org/apps/learn/

Tutorial: JSON Format

The beauty of JSON is it can stringify a multidimensional array, either indexed or associative array, into a linear string, so it can be passed between functions as well as languages. The basic rule is as follows:

1. If value is numeric, do not include the quote. If the value is string, include the double quote. For instance: 1, 3, "ab", "5". It is not necessary to use quote for the key in associative array if no whitespace used in key, else, use double quote. However, double quote on keys is required by JSON format specification.

2. Use ":" to separate key and value if the element is of associative relationship. For instance: Category_2:3.

3, use comma to separate elements. For instance: 1, Category_2:3, "ab".

4. Use [] to signify a single dimensional indexed array. For instance [1, 3, "ab"]. When calling an element within a single indexed dimensional array, just like usual: arr[2]. In this case, it would return 3.

5. Use {} to signify a single dimensional associative array. For instance {Category_2:3}. For multi-elements associative array, one bracket is enough: {Category_2:3, Category_3:"ab"}. When calling an element within a single associative dimensional array, use following format: arr.Category_3. In this case, it would return "ab".

Here is an example:

{lastName: "Smith",
age: 25,
address:
{streetAddress: "21 2nd Street",
postalCode: "10021"
},
phoneNumber:
[{ type: "home",
},
{ type: "fax",
number: "646 555-4567"
}
]
}

To get fax number here, call: arr.phoneNumber[1].number

Another example starts with index array:

[
{A:a}
,{B:b}
]

How to stringify JSON for multidimensional array? DON't use JavaScript built-in function stringify(). It does not work for multidimensional array. Use ''+arr to make it string.


http://en.wikipedia.org/wiki/Json

Issues In Multidimensional Array in JavaScript

Multidimensional array in JavaScript is treated as object, so it would be a problem when it works with dynamic HTML and Ajax. Since the reference points to the multidimensional array needs to be closely working with string, it is hard to program when should such reference being instantiated, that is presenting the whole body of the array rather than the reference itself. This issue becomes very serious when parameter management gets involved. Indeed, both bind variable and parameter management are essential for dynamic HTML.

If a string used as reference to be passed between functions, another issue may be occurred: hard to convert it back to reference. In some cases eval() function can be used to achieve this goal, however, it won't be able to work with multidimensional array.

The solution is using JSON datatype to represent the multidimensional array. In addition, it is suggested to convert it into string before being composed into bind variable or get involved with parameter management.


http://koncordpartners.blogspot.com/2010/08/parameter-management.html

‹div› and ‹span› in JavaScript

In JavaScript, neither dynamic HTML nor document.write() does work with string of entire ‹div› section. However, it is essential part of Dynamic HTML.

How to dynamically create a Div section in JavaScript? Follow is the codes from Toolbox for IT, edited by Smifis:

var newdiv = document.createElement('div');
newdiv.setAttribute('id', id);
if (width) {
newdiv.style.width = 300;
}
if (height) {
newdiv.style.height = 300;
}
if ((left || top) || (left && top)) {
newdiv.style.position = "absolute";
if (left) {
newdiv.style.left = left;
}
if (top) {
newdiv.style.top = top;
}
}
newdiv.style.background = "#00C";
newdiv.style.border = "4px solid #000";
if (html) {
newdiv.innerHTML = html;
} else {
newdiv.innerHTML = "nothing";
}
document.body.appendChild(newdiv);

Actually, there are two parts of it. The first part as listed above, which more or less like an defination. And the second part is to present the result. Esential scripts in 2nd part are:

; var painting = document.getElementById(id)
; painting.style.visibility = 'visible'
; if (content) painting.innerHTML = content

In addtion, you can move these arguable variable from first part to second part for dynamic purpose, such like x, y, width, height, background etc. What is suggested is to separate them into two functions:

; function drawFrame(frameId, posiType, borderPro, rightPro, bottomPro, bgc, classNam)
{ ; var newdiv = document.createElement('div')
; newdiv.setAttribute('id', frameId)
; newdiv.style.position = posiType
; if (bgc) newdiv.style.background = bgc
; if (borderPro) newdiv.style.border = borderPro
else
{ ; if (rightPro) newdiv.style.borderRight = rightPro
; if (bottomPro) newdiv.style.borderBottom = bottomPro
}
; newdiv.style.visibility = 'hidden'
; if (classNam) newdiv.setAttribute("class", classNam)
; document.body.appendChild(newdiv)
}

; function showFrame(frameId, wid, hei, xPos, yPos, content)
{ ; var painting = document.getElementById(frameId)
; if (0!=wid) painting.style.width = wid + 'px'
; if (0!=hei) painting.style.height = hei + 'px'
; painting.style.left = xPos + 'px'
; painting.style.top = yPos + 'px'
; painting.style.visibility = 'visible'
; if (content) painting.innerHTML = content
; return painting
}

Beware, you will need a "canvas" to draw the div section, such as body of HTML, or wondow.onload in JavaScript file.


http://it.toolbox.com/wiki/index.php/Dynamically_Creating_a_Div_in_Javascript

Get Latitude and Longitude Values from Google Maps

Following link provides an easy way to get latitude and longitude values from Google Maps:

http://www.tech-recipes.com/rx/2403/google_maps_get_latitude_longitude_values/

The contributor is qmchenry. Basically, copy following JavaScript into address bar of the browser, geodata of then center will be shown:

javascript:void(prompt('',gApplication.getMap().getCenter()));

The other ways include enabling LatLng Tooltip in Google Maps:

http://www.tech-recipes.com/rx/5519/the-easy-way-to-find-latitude-and-longitude-values-in-google-maps/

HTML Shows Nothing While Nothing Is Shown on Error Console

The most possible reason is either HTML or JavaScript codes are not clean. It often happens when you use Notepad to write codes. Another possibility is your JavaScript file is not accessible.

Trouble with Internet Explorer

The purpose of this article is to establish an uniform convention to deal with a very special issue of IE. It is for sure without this convention, websites would still run with or without problem. The issue is when IE passing null value from JavaScript to PHP, null value becomes string "null". If there is a possibility the user input could be "null", such as using "null" as login name or password, there is no way for PHP to detect which "null" is null and which "null" is input "null".

So, the accurate solution is never let JavaScript passing null to PHP, but using '' instead. It sounds easy; but JavaScript can generate null value without your knowledge. That is, if a parameter passing through a function to feed a form, when original parameter is undefined, eventually that undefined would be become string "null" or string "undefined" at the end of PHP. So, you would need to deal with every form input by special arrangement as follows:

; document.theForm.theInputItem.value = (parameter) ? parameter : ''

Then, to test if it is valid in JavaScript would be changed to:

; if (''!=parameter) {...}

At PHP end, it is relatively easy to detect if it is a valid input:

if (0!=strlen(trim(@$_POST["theInputItem"]))) {...};

However, for numeric data, it is not suitable to use '' instead null. It is still suggested to code as usual. The only difference is at PHP end:

if (0!=strlen(trim(@$_POST["theInputItem"])) && is_numeric(@$_POST["theInputItem"])) {...};


http://koncordpartners.blogspot.com/2009/12/test-various-nothings-in-php.html

Passing JavaScript Array to PHP by Using POST

Passing JavaScript Array to Php is not very popular. However, in some circumstances it becomes necessary; for instance, passing value of a group of checkboxes, using array would be most suitable setting.

In general, passing array is same as passing a variable. In HTML part, it looks:

<input type="checkbox" name="jsArray[1]" value="firstValue">
<input type="checkbox" name="jsArray[2]" value="secondValue">
<input type="checkbox" name="jsArray[3]" value="thirdValue">

The problem happens when HTML codes are generated dynamically or the value of checkbox is assigned dynamically. Normal assignment method, namely document.formName.inputItemName.value = something does not work. There is a suggestion in http://www.it-base.ro/2007/07/27/send-a-javascript-array-to-php/.

Another simply solution is to use id to assign the value:

; document.getElementById('inputItemId').value = something

Easy.

Convert PHP Array to JavaScript Array

<?php
////////////////////////////////////////////////////////////////////////////////////////////
// Universal function used to convert array in PHP to array in Javascript. //
// The result will be in string, includes declaration in Javascript, as well as the value //
// assigned to array in Javascript. //
// The array can be associative, as well as multidimensional, as many multidimensions as //
// you wish. This funcation is particularily useful when the number of elements and level //
// of multidimension is unknown. //
// Parameter $sJS is the string to represent the name of array in JS as you wish. //
////////////////////////////////////////////////////////////////////////////////////////////

function arrayToJavascript($aPHP, $aJS) // This is to deal with first level of recursion.
{
$lenFirst = @count($aPHP); // "@" deals with PHP Error Massage.
if (0!=$lenFirst && is_array($aPHP)) // Test if this is valid array or if reached the end of array.
{
echo "var ".$aJS." = new Array(".$lenFirst.");\n"; // Declare first level of array.
foreach ($aPHP as $key => &$value)
{
if (is_numeric($key))
{
$arrayString = $aJS."[".$key."]"; // Javascript variable.
}
else
{
$arrayString = $aJS."['".$key."']"; // Javascript variable.
};
toJSrecur($arrayString, $aPHP[$key]);
};
}
else
{
echo "Input is not a valid PHP array.";
};
}

function toJSrecur($arrayJS, $element) // This is to deal with standard level of recursion.
{ $len = @count($element); // count() does cause the trouble when reach the end of array.
if (0!=$len && is_array($element))
{
echo $arrayJS." = new Array(".$len.");\n"; // Declare each level of array.
foreach ($element as $key => &$value)
{
if (is_numeric($key))
{
$newString = $arrayJS."[".$key."]"; // Javascript variable.
}
else
{
$newString = $arrayJS."['".$key."']"; // String, is to be used by the echo at next level.
};
toJSrecur($newString, $element[$key]);
};
}
else // Start to write into javascript array at end of each branch in the recursion.
{
if ($element)
{
if (is_numeric($element))
{
$eleValue = $element;
}
else // Sign "'" in Javascript does cause trouble. Escape is needed.
{
$eleValue = "'".str_replace("'", "\'", $element)."'";
};
}
else
{
$eleValue = "''";
};
echo $arrayJS." = ".$eleValue.";\n"; // Assign values when the branch reached the end.
};
}

?>

Sequential and Modular Programming

Modular Programming came out as a newer technique. In terms sequence to execute the programing blocks, or called modules, modular programming also means the run time automatically searching where the modules are. Unfortunately, different language sets it differently, some are better and some are not so good. Object-oriented languages are all modular programming and they are the best in this regarding.

PL/SQL

PL/SQL is sequential language and its modules searching function is very bad. It means you would have to put functions/procedures in right order within the package to enable the sequential process. Of course, for packages itself it has no problem since packages are individual files.

Java

Java is a fully object-oriented language, though within the class, it is still the sequential. However, methods within the class are also fully modularized. It means the position of methods plays no role, and can be found by run time automatically.

JavaScript

Although JavaScript is classified as object-oriented language, only functions in root level in the file are modularized. Within the function, while it is sequential, nested functions are not fully modularized. It means within the function, your nested functions need to be placed in right order before it can be called. Even in root level, variablized functions still need to be treated carefully with the order. In particular, some built-in functions are very sensitive to the sequence, such as setTimeout() and setInterval().


http://en.wikipedia.org/wiki/Modular_programming
http://en.wikipedia.org/wiki/Javascript
http://koncordpartners.blogspot.com/2010/04/function-declaration-in-javascript.html

Function Declaration in JavaScript

It is easy to declare a function in JavaScript. And everyone knows it:

Standard or Procedural Function

; function func()
{
...
}

The problem of it is this function cannot be passed as parameter in another function. To be able to do that, you will need to varibalize it:

Varibalized Function, or Function Literal, Function Reference, Function Pointer

; var func = function()
{
...
}

Everyone does that too. Wait a moment. This form for declaration indeed is just set to fail if you use it carelessly. You may get following error massage when sequence to execute programming block becoming sensitive, such as work with setTimeout() and setInvertal() or inside of a function:

[This function] is not defined.

If you include this form of function with setInterval or setTimeout, you may get error message:

useless setInterval call (missing quotes around argument?)

This is because you will need to put it in right sequence to make sure the memory has load the function first.

So, it is suggested in general you should use orthodox function declaration method. If you use variablized function declaration method, please make sure it has been put into right place in the sequence of programming blocks.

Have a look at following case:

; var func = func()

; function func()
{
...
}

No, this is not a function declaration method for first statement. It just get the return value from the function func().

Apart from above mentioned popular method, here is

Function Object

; var func = new Function()
{
...
}

It is not recommended to use because it would take longer time to process, unless for special purpose, such as reconstruct to function from variablized function and variablized parameters. For instance:

; var reconstructedVar = new Function([para1, para2,...paran], functionBody)
{
...
}

Please take note, all parameters and function body must be in string or reference. The other way to reconstruct the function is to do it by yourself. For details, please see Passing Function in JavaScript.


http://www.permadi.com/tutorial/jsFunc/index.html
http://www.hunlock.com/blogs/Functional_Javascript
http://www.dustindiaz.com/javascript-function-declaration-ambiguity/
http://osdir.com/ml/jQuery/2009-11/msg01942.html
Javascript Error Message: is not a function

Strange Behavior Between onkeydown And onkeypress Events

A strange behavior between onkeydown and onkeypress events in JavaScript has been noticed. Here is a function to find out the keycode:

; function getCode(e)
{
; var evt = window.event ? event : e
; var code
; if(window.event) code = evt.keyCode
else code = evt.which
; return code
}

If the event is onkeypress, this function would generate ASCII key code. However, if the event is onkeydown, this function would generate JavaScript keycode, which does not discriminated the cases. Indeed, the latter generate keycode for capital case only.

Passing Function in JavaScript

To pass function like a reference, one needs first to make the function a variable reference:

; var funcationName = function(argu) { ... }

Then, it can be passed:

; function anotherFunc(passingFunc)
{
; passingFunc(para)
}

Use it just like the function itself. Indeed, if there is no parameter for functionName(), you will still need to use it as function:

; function anotherFunc(passingFunc)
{
; passingFunc()
}

Function passing even can be used to across the html pages, just like variable reference passing:

; function anotherFunc(passingFunc)
{
; parent.passingFunc()
}

In HTML, following syntax is used to invoke the function:

onkeypress="anotherFunc(funcationName)"

It is very important, the sign of () could NOT be put in invokin statement in HTML, something like:

onkeypress="anotherFunc(funcationName())"

Now, this syntax does create confusion when you want to pass the parameter as will, for instance, you want to call anotherFunc(funcationName(argu)). The ways to overcome it is:

1. For static passing function with dynamic passing varialbe: Declare argu as global variable. Codes are as follows:

; var para

; var funcationName = function(argu) { ... }

; function anotherFunc(passingFunc)
{
; passingFunc(para)
}

onkeypress="para=something;anotherFunc(funcationName)"

3. If you want a complete dynamic passing function together with a dynamic passing variable, you will need to create third function:

; var para

; var funcationName = function(argu) { ... }

; var thirdFunc = function()
{
...
; funcationName(para)
...
}

; function anotherFunc(passingFunc)
{
; passingFunc()
}

onkeypress="para=something;anotherFunc(thirdFunc)"

Function thirdFunc() indeed is where you should play with.

Another approach is to write a function to reconstruct the function from variables:

; function reconstructFunc(func, totalPara, para1, para2, para3)
{
; var newFunc
; if (0==totalPara) newFunc = func
else if (1==totalPara)
{
; newFunc = function()
{
; func(para1)
}
}
else if (2==totalPara)
{
; newFunc = function()
{
; func(para1, para2)
}
}
else
{
; newFunc = function()
{
; func(para1, para2, para3)
}
}
; return newFunc
}

It is very important when passing function, the function must be properly declared. Please refer to http://koncordpartners.blogspot.com/2010/04/function-declaration-in-javascript.html. This article also covers another method to reconstruct the function from variablized function and parameters.

If the function reference/literal had passed across HTML pages, in IE 8 it might general error as "Function expected". To overcome this, you need to set up a local variablized function to call access remote function.

Labels