Wednesday

Remote Scripting with IFRAME

As web sites become more and more like traditional applications, the call-response-reload model used in HTTP transactions becomes increasingly cumbersome. Instead of delivering a single dynamic page, the DHTML or JavaScript developer must create a series of separate pages. The flow of the application is interrupted by page reloads whenever the client communicates with the server. Remote scripting provides a solution to this problem, easing development of complex JavaScript applications, and providing a better experience for the end user.

What is Remote Scripting?

Remote Scripting is the process by which a client-side application running in the browser and a server-side application can exchange data without reloading the page. Remote scripting allows you to create complex DHTML interfaces which interact seamlessly with your server.

If you're not clear on exactly what this means, think of the ever-present JavaScript image swap (you've coded one of those, haven't you?). In an image swap, your client-side code requests new data from the server to be displayed on the web page; in this case the request made to the server is for a new image with which you wish to replace an existing image. But what if you could ask the server for something other than an image? What if you could request a block of text? And what if your request could be more than a simple call for data? What if you could submit form data back to the server, have the server process that data and respond with an appropriate message? Of course, all of these things are already possible by relying on page reloads, but remote scripting allows complex interaction with the server that appears as seamless to the user as a simple image swap.

Remote scripting is a form of RPC (Remote Procedure Call), which is a general term used to describe the exchange of data between remote computer systems. Remote scripting opens up a great number of opportunities for the developer. Imagine a news article that can load side bars and graphical information related to the article directly into the web page when the site's visitors request it. Imagine a gallery of photo thumbnails that turn into full-sized images when clicked. Imagine a full-featured, browser-based content management system interface that allows a site administrator to edit web site copy in situ. The possibilities are limited only by the creativity of the developer.

Setting up Remote Scripting

As I'm sure you've gathered, remote scripting is a client/server technology that relies on two distinct components: the server, which is your web server, and the client, which is the JavaScript application in your web page. In remote scripting, you'll be making an RPC from your JavaScript application to your server. You'll need to be versed in both client and server web technologies to get started with remote scripting.

The client-side component is a part of the web page that you want to enable with remote scripting capabilities. It needs to be able to make a call back to the server, usually done via HTTP, and to then be able to receive and deal with the server response, if any. The server component must be ready to receive requests from the client, process the request, and then respond, returning data to the client if needed. The server component can be a script served up by your web server, such as a .php, .asp, or .cgi file, or it can be a dedicated software package that handles only RPC calls, or it can even be a simple database comprised of static files.

As you can see, the requirements for each of these components will vary greatly depending on how you choose to implement your remote scripting system.

Remote Scripting Technology Options

Remote scripting is actually a fairly broad term, and does not necessarily imply the use of any particular technology. Several remote scripting options are available to the web developer:

Java Applet/ActiveX control/Flash By embedding an ActiveX component, a Java applet, or a Flash movie into your web page, all of which are capable of making HTTP requests and interacting with your client-side JavaScript code, you can implement the client component of a remote scripting system. Not all browsers support the technology (called LiveConnect) that allows for interaction between JavaScript and such objects; most notably, IE5 Mac does not support it at all, and NS6 (on all platforms) has such splotchy support it cannot really be called support at all. In addition to those problems, using an embedded object for remote scripting requires the end-user to install additional proprietary software. ActiveX does not work on the Macintosh platform, and Java can cause some difficulties with some versions of Internet Explorer. On the upside, Java and ActiveX can create socket connections with the server, which allows the server to interact with your application even when communication is not initiated by the client component. Unless you're developing in an environment where browser homogeneity can be assumed, these technologies may not be a good choice for remote scripting.

XML-RPC is in many ways the superior choice for remote scripting. It uses XML for encapsulating data, HTTP for its transport mechanism, and can be implemented in a wide variety of platform and software environments. XML-RPS is an open, standards-based technology that is quickly becoming the de-facto method for RPC of all kinds. The down side is that it takes a bit more know-how and work to get it up and running, requiring the installation of XML-RPC libraries on your server and in your client-side code. It also does not work with IE5 on the Macintosh.

Simple HTTP via a hidden IFRAME Using an IFRAME in conjunction with a script on your web server or a database of static HTML files, is by far the easiest of the remote scripting options available. The IFRAME has been part of the HTML specification since version 4 and is supported in nearly all modern browsers. On the server, you can use your scripting language of choice to process page requests made to the IFRAME. In the remainder of this article you'll see how to implement these components.

Using an IFRAME for Remote Scripting

Enough already with the talk! Let's get to the code. I'm going to show you everything you need to know to set up a remote scripting system with an IFRAME. I'll start with the basic set up, and describe some common browser problems and their solutions.

For starters, you'll need two web pages. The first should be called client.html (or some variation thereof, depending on the example). It will be the main working document and will contain nearly all of the scripts. The client.html will be making remote scripting calls using an IFRAME embedded in the document's HTML. The second page will be server.html. In a live server environment, you'd call it server.php, or server.asp, or whatever extension fits your server platform, but in this example we're not using a dynamic server component, so an .html extension is fine.

The client.html file will make RPC calls by passing arguments to server.html in the query string. The server.html will process the RPC, and write out a very simple page which contains script calls back to client.html. This will be clearer after we look at a simple example.

In client.html enter the following:





make RPC call

As you can see, in it's simplest form IFRAME remote scripting simply points the TARGET attribute of a link to a hidden IFRAME. You can hide an IFRAME by setting its WIDTH, HEIGHT, and BORDER properties to 0px. Don't use display:none, because NS6 ignores IFRAMEs when the display property is set to none. If you were using the above code with display:none set for the IFRAME, the contents of server.html would load into the main client.html document, not into the IFRAME.

In server.html use the following HTML:


The handleResponse() function is found in our client.html page, and we simply use the parent property of the IFRAME document's window object to call it. See it in action here. Of course you notice that in this example we are not actually processing anything on the server. If you want, on your server go ahead and change your server page code to something like this (I'm using ASP as an example server scripting language):


And change the handleResponse() function in client.html to something like this:


You should now get an alert message containing information returned from your server, the results of your first remote procedure call!

Should you want to pass data to server.html, you can either embed it in the query string of the URL specified in your link, or, to allow user interaction, use a form instead of a link, like so:




Just like the link, you specify the IFRAME as the target of your form, use server.html to process the form data on the server, and send any data back with the handleResponse() method. More on working with forms later.

Problems and Solutions

You may have already realized that there are some serious problems with this simplest of remote scripting scenarios. Perhaps most seriously, this method renders the "back" and "reload" buttons in most browsers useless. Because the loading of server.html in the IFRAME is added to the browsers history object, hitting the reload button after you've loaded server.html, for instance, reloads server.html in the IFRAME instead of reloading client.html as would be expected.

NOTE: You may or not experience this problem, depending on a combination of factors including your browser version, server platform, HTTP headers, and browser settings. Trust me, if you simply target a link at an IFRAME, some users will have problems with their reload and back buttons.

A new function called callToServer() handles this problem by using the replace() method of the IFRAME document's document object. In addition, instead of creating an IFRAME element in the HTML, I'll let callToServer() create the IFRAME through the wonders of the DOM. Doing so alleviates all the reload and back button problems, and keeps the mark up free from unneeded tags.

Sadly, referencing the IFRAME's document object is no simple task, since IE5, IE5.5, IE6, and NS6 all provide different ways to access it. IE5, both on the Mac and PC, provides the simplest method: IFRAMEs in this browser show up in the document.frames array and have a document property. In IE5.5, IE6 and NS6, you can retrieve the IFRAME element object with document.getElementByID(), then, in NS6, use the object's contentDocument property, and in IE 5.5+, use the document property of the IFRAME object's contentWindow property. That's quite a mouthful, isn't it? Thankfully, it's quite a bit simpler in the actual code:

var IFrameObj; // our IFrame object
function callToServer() {
if (!document.createElement) {return true};
var IFrameDoc;
var URL = 'server.html';
if (!IFrameObj && document.createElement) {
// create the IFrame and assign a reference to the
// object to our global variable IFrameObj.
// this will only happen the first time
// callToServer() is called
try {
var tempIFrame=document.createElement('iframe');
tempIFrame.setAttribute('id','RSIFrame');
tempIFrame.style.border='0px';
tempIFrame.style.width='0px';
tempIFrame.style.height='0px';
IFrameObj = document.body.appendChild(tempIFrame);

if (document.frames) {
// this is for IE5 Mac, because it will only
// allow access to the document object
// of the IFrame if we access it through
// the document.frames array
IFrameObj = document.frames['RSIFrame'];
}
} catch(exception) {
// This is for IE5 PC, which does not allow dynamic creation
// and manipulation of an iframe object. Instead, we'll fake
// it up by creating our own objects.
iframeHTML='\

courtsy: apple.com

Thursday

Create sub domain application with PHP

First you need to set your main domain to act as a catch-all subdomain. its like putting ServerAlias * so that each subdomain which is requested
to the main domain reaches the same place. I mean if your main domain root is

/home/admin/abc.com/htdocs/

then your catch-all setup shall send all sub-domain requests to that same directory

/home/admin/abc.com/htdocs/

and then in the index.php file of this directory you can do this

global $domainname;
global $subdomainname;
$domainarray = explode('.', $_SERVER['HTTP_HOST']);
$index=count($domainarray)-1;
$domainname= $domainarray[$index-1].".".$domainarray[$index];
$subdomainname="";
for($i=0;$i<$index-1;$i++)
{
if($subdomainname=="")
{
$subdomainname=$domainarray[$i];
}
else
{
$subdomainname=$subdomainname.".".$domainarray[$i];
}

}

ShowCustomizedPageForsubdomain($subdomainname);

?>

This function ShowCustomizedPageForsubdomain($subdomainname) can be easily implemented in two ways:

1) Either your store Page's Html in your database and all this function would do is to pick up that html code for the provided sub-domain from the database and simply
"echo" or "print" it.
2) or you can simply have standard actual pages for each subdomain and you simply include them here like this

ob_start();
include "http://url_of_the_page_you_want_to_show";
$data=ob_get_contents();
ob_clean();

this Object buffer will return you that page's content in the variable "$data"; you simply echo $data;

Second Implementation of your function is like this

function ShowCustomizedPageForsubdomain($subdomainname)
{
ob_start();
include "http://url_of_the_page_you_want_to_show_for_this_subdomain";
$data=ob_get_contents();
ob_clean();
echo $data;
}

Monday

PHP OOP

New Functionality
Support for PPP Exceptions Object Iteration Object Cloning Interfaces Autoload And much more, and it is faster too!

The Basics
The basic object operations have not changed since PHP 4.
class my_obj { var $foo; function my_obj() { // constructor $this->foo = 123; } function static_method($a) { return urlencode($a); } } $a = new my_obj; // instantiate an object $a->my_obj(); // method calls my_obj::static_method(123); // static method call

Similar, but not the same.
While the syntax remains the same, internals are quite different.  Objects are now always being passed by reference, rather then by value.
PHP 5 $a = new foo(); == PHP4 $a = &new foo();

While the old style constructors are supported, new more consistent mechanism is available. __construct() method.

PPP Annoyance
The VAR keyword for identifying class properties became deprecated and will throw an E_STRICT warning.
PHP Strict Standards: var: Deprecated. Please use the public/private/protected modifiers in obj.php on line 3.

Instead, you should use PUBLIC, PRIVATE or PROTECTED keywords.

PHP 5 Ready Code
foo = 123; } // static methods need to be declared as static // to prevent E_STRICT warning messages. static function static_method($a) { return urlencode($a); } } $a = new my_obj; my_obj::static_method("a b"); ?>

PHP 5 Constructors
In PHP 5 parent::__construct will automatically determine what parent constructor is available and call it.
class main { function main() { echo "Main Class\n"; } } class child extends main { function __construct() { parent::__construct(); echo "Child Class\n"; } } $a = new child;

Destructors
Destructor methods specifies code to be executed on object de-initialization.
class fileio { private $fp; function __construct ($file) { $this->fp = fopen($file, "w"); } function __destruct() { // force PHP to sync data in buffers to disk fflush($this->fp); fclose($this->fp); } }

Objects by Reference
No matter how an object is passed in PHP 5+, you always work with the original.
function foo($obj) { $obj->foo = 1; } $a = new StdClass; foo($a); echo $a->foo; // will print 1 class foo2 { function __construct() { $GLOBALS['zoom'] = $this; $this->a = 1; } } $a = new foo2(); echo ($a->a == $zoom->a); // will print 1

What If I Want a Copy?
To copy an object in PHP 5 you need to make use of the clone keyword.  This keyword does the job that $obj2 = $obj; did in PHP 4.

Choices Choices Choices
Being a keyword, clone supports a number of different, but equivalent syntaxes.
class A { public $foo; } $a = new A; $a_copy = clone $a; $a_another_copy = clone($a); $a->foo = 1; $a_copy->foo = 2; $a_another_copy->foo = 3; echo $a->foo . $a_copy->foo . $a_another_copy->foo; // will print 123

Extending Clone
__clone() can be extended to further modify the newly made copy.
class A { public $is_copy = FALSE; public function __clone() { $this->is_copy = TRUE; } } $a = new A; $b = clone $a; var_dump($a->is_copy, $b->is_copy); // false, true

PPP
Like in other OO languages, you can now specify the visibility of object properties, for the purposes of restricting their accessibility.
PUBLIC – Accessible to all.  PROTECTED – Can be used internally and inside extending classes.  PRIVATE – For class’ internal usage only.

PPP in Practice
a . $this->b . $this->c; } } class miniSample extends sample { function __construct() { echo $this->a . $this->b . $this->c; } } $a = new sample(); // will print 123 $b = new miniSample(); // will print 13 & notice about undefined property miniSample::$b echo $a->a . $a->b . $a->c; // fatal error, access to private/protected property ?>

Practical PPP Applications
$v) { if (isset($_POST[$k])) { $a->$k = $_POST[$k]; } } ?>

Not all PHP functions/constructs respect, PPP visibility rules

Static Properties
Another new feature of PHP 5 objects, is the ability to contain static properties.
login; // undefined property warning $a->login = "Local Value"; // parse error? (NOPE!) echo $a->login; // will print "Local Value" ?>

Class Constants
PHP 5 also supports class constants, which are very similar to static properties, however their values can never be altered.
class cc { const value = 'abc 123'; function print_constant() { // access class constants inside of the class echo self::value; } } echo cc::value; // access class constants outside of the class

PPP Applies to Methods Too!
Method access can also be restricted via PPP.
Hide and prevent access to application’s internal functionality.  Data separation.  Increased security. Cleaner Code.

Practical PPP Methods
class mysql { private $login, $pass, $host; protected $resource, $error, $qp; private function __construct() { $this->resource = mysql_connect($this->host, $this->login, $this->pass); } protected function exec_query($qry) { if (!($this->qp = mysql_query($qry, $this->resource))) { self::sqlError(mysql_error($this->resource)); } } private static function sqlError($str) { open_log(); write_to_error_log($str); close_log(); } }

Practical PPP Methods
class database extends mysql { function __construct() { parent::__construct(); } function insert($qry) { $this->exec_query($qry); return mysql_insert_id($this->resource); } function update($qry) { $this->exec_query($qry); return mysql_affected_rows($this->resource); } }

Final
PHP 5 allows classed and methods to be defined a FINAL.
For methods it means that they cannot be overridden by a child class.  Classes defined as final cannot be extended.

Final Method Example
By making a method FINAL you prevent and extending classes from overriding it. Can be used to prevent people from re-implementing your PRIVATE methods.
class main { function foo() {} final private function bar() {} } class child extends main { public function bar() {} } $a = new child();

Final Class Example
Classes declared as final cannot be extended.
final class main { function foo() {} function bar() {} } class child extends main { } $a = new child();
PHP Fatal error: Class child may not inherit from final class (main)

Autoload
Maintaining class decencies in PHP 5 becomes trivial thanks to the __autoload() function.

If defined, the function will be used to automatically load any needed class that is not yet defined.

Magic Methods
Objects in PHP 5 can have 3 magic methods.
__sleep() – that allows scope of object serialization to be limited. (not new to PHP)  __wakeup() – restore object’s properties after deserialization.  __toString() – object to string conversion mechanism.

Serialization
Serialization is a process of converting a PHP variable to a specially encoded string that can then be used to recreate that variable. Needed for complex PHP types such as objects & arrays that cannot simply be written to a file or stored in a database. The serialization process is done via serialize() and restoration of data via unserialize() functions.

Serialize Example
class test { public $foo = 1, $bar, $baz; function __construct() { $this->bar = $this->foo * 10; $this->baz = ($this->bar + 3) / 2; } } $a = serialize(new test()); // encode instantiated class test $b = unserialize($a); // restore the class into $b;

The encoded version of our object looks like this:
O:4:"test":3:{s:3:"foo";i:1;s:3:"bar";i:10;s:3:"baz";d:6.5;}

__sleep()
The __sleep() method allows you to specify precisely which properties are to be serialized.

class test { public $foo = 1, $bar, $baz; function __construct() { $this->bar = $this->foo * 10; $this->baz = ($this->bar + 3) / 2; } function __sleep() { return array('foo'); } }

This makes our serialized data more manageable.
O:4:"test":1:{s:3:"foo";i:1;}

__wakeup()
__wakeup(), if available will be called after deserialization. It’s job is to recreate properties skipped during serialization.
class test { public $foo = 1, $bar, $baz; function __construct() { $this->bar = $this->foo * 10; $this->baz = ($this->bar + 3) / 2; } function __wakeup() { self::__construct(); } }

__toString()
Ever wonder how PHP extensions like SimpleXML are able to print objects and output valid data rather then garbage?
Ilia'); var_dump($xml->data); echo $xml->data; ?>

Output:
object(SimpleXMLElement)#2 (1){ [0]=> string(4) "Ilia" } Ilia

Sample __toString()
foo = rand(); } function __toString() { return (string)$this->foo; } } echo new Sample(); ?>

__toString() Gotchas
Assuming $a = new obj();     echo echo echo echo "str" . $a; "str {$a}" $a{0}; ** (string) $a;

In all of these instances __toString() will not be called.

Overloading
Both method calls and member accesses can be overloaded via the __call, __get and __set methods.  Provide access mechanism to “virtual” properties and methods.

Getter
The getter method, __get() allows read access to virtual object properties.
class makePassword { function __get($name) { if ($name == 'md5') return substr(md5(rand()), 0, 8); else if ($name == 'sha1') return substr(sha1(rand()), 0, 8); else exit(“Invalid Property Name”); } } $a = new makePassword(); var_dump($a->md5, $a->sha1);

Setter
The setter method, __set() allows write access to virtual object properties.

Dynamic Methods
The __call() method in a class can be used to emulate any non-declared methods.
class math { function __call($name, $arg) { if (count($arg) > 2) return FALSE; switch ($name) { case 'add': return $arg[0] + $arg[1]; break; case 'sub': return $arg[0] - $arg[1]; break; case 'div': return $arg[0] / $arg[1]; break; } } }

Important Overloading Reminders
The name passed to __get, __set, __call is not case normalized. $foo->bar != $foo->BAR  Will only be called if the method/property does not exist inside the object.  Functions used to retrieve object properties, methods will not work.  Use with caution, it takes no effort at all to make code terribly confusing and impossible to debug.

Object Abstraction
Abstract classes allow you to create set methods describing the behavior of a to be written class.

Database Abstraction
The methods preceded by abstract keyword must be implemented by the extending classes.
abstract class database { public $errStr = '', $errNo = 0; // these abstract abstract abstract abstract abstract abstract } methods must be provided by extending classes protected function init($login,$pass,$host,$db); protected function execQuery($qry); protected function fetchRow($qryResource); protected function disconnect(); protected function errorCode(); protected function errorNo();

Abstract Implementer
class mysql extends database { private $c; protected function init($login, $pass, $host, $db) { $this->c = mysql_connect($host, $login, $pass); mysql_select_db($db, $this->c); } protected function execQuery($qry) { return mysql_query($qry, $this->c); } protected function fetchRow($res) { return mysql_fetch_assoc($res); } protected function errorCode() {return mysql_error($this->c); } protected function errorNo() { return mysql_errno($this->c); } protected function disconnect() { mysql_close($this->c); } }

Interfaces
Object interfaces allows you to define a method “API” that the implementing classes must provide.

Interface Examples
Interfaces are highly useful for defining a standard API and ensuring all providers implement it fully.
interface webSafe { public function public function } interface sqlSafe { public function public function } encode($str); decode($str);

textEncode($str); binaryEncode($str);

Implementer
A class can implement multiple interfaces.
class safety Implements webSafe, sqlSafe { public function encode($str) { return htmlentities($str); } public function decode($str) { return html_entity_decode($str); } public function textEncode($str) { return pg_escape_string($str); } public function binaryEncode($str) { return pg_escape_bytea($str); } }

ArrayAccess Interface
One of the native interface provided by PHP, allows object to emulate an array.  The interface requires the following :
offsetExists($key) - determine if a value exists  offsetGet($key) - retrieve a value  offsetSet($key, $value) - assign value to a key  offsetUnset($key) - remove a specified value

ArrayAccess in Action
class changePassword implements ArrayAccess { function offsetExists($id) { return $this->db_conn->isValidUserID($id); } function offsetGet($id) { return $this->db_conn->getRawPasswd($id); } function offsetSet($id, $passwd) { $this->db_conn->setPasswd($id, $passwd); } function offsetUnset($id) { $this->db_conn->resetPasswd($id); } } $pwd = new changePassword; isset($pwd[123]); // check if user with an id 123 exists echo $pwd[123]; // print the user’s password $pwd[123] = “pass”; // change user’s password to “pass” unset($pwd[123]); // reset user’s password

Object Iteration
To use it an object  PHP 5 allows an must implement the object to following methods: implement an  rewind internal iterator  current interface that will  key specify exactly how  next an object is to be  valid iterated through.

File Iterator
class fileI Implements Iterator { private $fp, $line = NULL, $pos = 0; function __construct($path) { $this->fp = fopen($path, "r"); } public function rewind() { rewind($this->fp); } public function current() { if ($this->line === NULL) { $this->line = fgets($this->fp); } return $this->line; } }

File Iterator Cont.
public function key() { if ($this->line === NULL) { $this->line = fgets($this->fp); } if ($this->line === FALSE) return FALSE; return $this->pos; } public function next() { $this->line = fgets($this->fp); ++$this->pos; return $this->line; } public function valid() { return ($this->line !== FALSE); }

File Iterator Cont.
$v) { echo "{$k} {$v}"; } ?> 0 1 2 3 4 5 6 7 $v) { echo "{$k} {$v}"; } ?>

Output:
Exceptions
Exceptions are intended as a tool for unifying error handling.  An entire block of code can be encompassed inside a try {} block.  Any errors, are then sent to the catch {} for processing.

Native Exception Class
class Exception { protected $message = 'Unknown exception'; // exception message protected $code = 0; // user defined exception code protected $file; // source filename of exception protected $line; // source line of exception function __construct($message = null, $code = 0); final final final final final final }

function function function function function function

getMessage(); // message of exception getCode(); // code of exception getFile(); // source filename getLine(); // source line getTrace(); // backtrace array getTraceAsString(); // trace as a string

function __toString(); // formatted string for display

Exception Example
getFile(), $e->getLine(), $e->getMessage()); exit; } ?>

Extending Exceptions
class iliaException extends Exception { public function __construct() { parent::__construct($GLOBALS['php_errormsg']); } public function __toString() { return sprintf("Error on [%s:%d]: %s\n", $this->file, $this->line, $this->message); } } ini_set("track_errors", 1); error_reporting(0); try { $fp = fopen("m:/file", "w"); if (!$fp) throw new iliaException; if (fwrite($fp, "abc") != 3) throw new iliaException; if (!fclose($fp)) throw new iliaException; } catch (iliaException $e) { echo $e; }

Stacking & Alternating Exceptions
$a = new dbConnection(); $a->execQuery(); $a->fetchData(); (ConnectException $db) {

} catch (QueryException $qry) { } catch (fetchException $dt) { } ?>

 PHP Exceptions can be stackable or alternate based on the exception name.

Exception Handler
The exception handler function, set_exception_h andler() allows exceptions to be handled without explicitly listing the try {} catch () {} block.
function exHndl($e) { trigger_error($e->getLine()); } set_exception_handler('exHndl'); $fp = fopen("m:/file", "w"); if (!$fp) throw new iliaException; if (fwrite($fp, "abc") != 3) throw new iliaException; if (!fclose($fp)) throw new iliaException;

Type Hinting
While PHP is still type insensitive, you can now specify what type of objects your functions and methods require.

Reflection API
Reflection API provides a mechanism for obtaining detailed information about functions, methods, classes and exceptions.  It also offers ways of retrieving doc comments for functions, classes and methods.

Reflection Mechanisms
The API provides a distinct class for study of different entities that can be analyzed.

Tuesday

Language conversion with Google API and Ajax

Introduction The "Hello, World" of the Google AJAX Language API

The easiest way to start learning about this API is to see a simple example. The following example will detect the language of the given text and then translate it to English.

<html>
<head>
<script type="text/javascript" src="http://www.google.com/jsapi">script>
<script type="text/javascript">
google
.load("language", "1");
function initialize() {
var text = document.getElementById("text").innerHTML;
google
.language.detect(text, function(result) {
if (!result.error && result.language) {
google
.language.translate(text, result.language, "en",
function(result) {
var translated = document.getElementById("translation");
if (result.translation) {
translated
.innerHTML = result.translation;
}
});
}
});
}
google
.setOnLoadCallback(initialize);
script>
head>
<body>
<div id="text">你好,很高興見到你。div>
<div id="translation">div>
body>
html>

You can view this example here to edit and play around with it.

Including the AJAX Language API on Your Page

To include the AJAX Language API in your page, you will utilize the Google AJAX API loader. The common loader allows you to load all of the AJAX apis that you need, including the language API. You need to both include the Google AJAX APIs script tag and call google.load("language", "1"):

<script type="text/javascript" src="http://www.google.com/jsapi">script>
<script type="text/javascript">
google
.load("language", "1");
script>

The first script tag loads the google.load function, which lets you load individual Google APIs. google.load("language", "1") loads Version 1 of the Language API. Currently the AJAX Language API is in Version 1, but new versions may be available in the future. See the versioning discussion below for more information.

API Updates

The second argument to google.load is the version of the AJAX Language API you are using. Currently the AJAX Language API is in version 1, but new versions may be available in the future.

If we do a significant update to the API in the future, we will change the version number and post a notice on Google Code and the AJAX APIs discussion group. When that happens, we expect to support both versions for at least a month in order to allow you to migrate your code.

The AJAX Language API team periodically updates the API with the most recent bug fixes and performance enhancements. These bug fixes should only improve performance and fix bugs, but we may inadvertently break some API clients. Please use the AJAX APIs discussion group to report such issues.

Examples

Language Translation

This example shows a simple translation of a javascript string.

google.language.translate("Hello world", "en", "es", function(result) {
if (!result.error) {
var container = document.getElementById("translation");
container
.innerHTML = result.translation;
}
});

View example (translate.html)

Language Detection

This example shows language detection of a javascript string. The language code is returned

var text = "¿Dónde está el baño?";
google
.language.detect(text, function(result) {
if (!result.error) {
var language = 'unknown';
for (l in google.language.Languages) {
if (google.language.Languages[l] == result.language) {
language
= l;
break;
}
}
var container = document.getElementById("detection");
container
.innerHTML = text + " is: " + language + "";
}
});

View example (detection.html)

Source Detection during Translation

The following example is similar to the basic translation example but shows how to translate the text without knowing the source language. By specifying an empty string as unknown for the source language, the system will detect and translate in one call.

google.language.translate("Hello world", "", "es", function(result) {
if (!result.error) {
var container = document.getElementById("translation");
container
.innerHTML = result.translation;
}
});

View example (autotranslate.html)

Branding and Google Attribution

When your application uses the Google AJAX Language APIs, it is important to communicate the Google brand to your users. The google.language.getBranding() method is designed to help with this. The method accepts an HTML DOM element or the corresponding id, as well as optional options. The branding is attached to the provided element.

// attach a "powered by Google" branding
<div id='branding'> </div>
...
google.language.getBranding('branding');

The branding can be customized via CSS and comes in a 'vertical' and 'horizontal' base formats. An example showing the various formats and CSS customization is below.

View example (branding.html)

Some Additional Samples

Here are two addional samples that allow some interaction. The first does language detection with a pre-canned text string but allows other text to be input. It also display confidence and reliability factors.

View example (detect.html)

The second additional sample does translation. However it will also allow interaction similar to the sample above.

View example (translate.html)

API Details
Supported Languages

The Google AJAX Language API currently supports the following languages. The technology is constantly improving and the team is working hard to expand this list, so please check back often. You can also visit Google Translate to view an up to date list.

  • Afrikaans New!
  • Albanian New!
  • Amharic New!
  • Arabic
  • Armenian New!
  • Azerbaijani New!
  • Basque New!
  • Belarusian New!
  • Bengali New!
  • Bihari New!
  • Bulgarian New!
  • Burmese New!
  • Catalan New!
  • Cherokee New!
  • Chinese (Simplified and Traditional)
  • Croatian New!
  • Czech New!
  • Danish New!
  • Dhivehi New!
  • Dutch
  • English
  • Esperanto New!
  • Estonian New!
  • Filipino New!
  • Finnish New!
  • French
  • Galician New!
  • Georgian New!
  • German
  • Greek
  • Guarani New!
  • Gujarati New!
  • Hebrew New!
  • Hindi New!
  • Hungarian New!
  • Icelandic New!
  • Indonesian New!
  • Inuktitut New!
  • Italian
  • Japanese
  • Kannada New!
  • Kazakh New!
  • Khmer New!
  • Korean
  • Kurdish New!
  • Kyrgyz New!
  • Laothian New!
  • Latvian New!
  • Lithuanian New!
  • Macedonian New!
  • Malay New!
  • Malayalam New!
  • Maltese New!
  • Marathi New!
  • Mongolian New!
  • Nepali New!
  • Norwegian New!
  • Oriya New!
  • Pashto New!
  • Persian New!
  • Polish New!
  • Portuguese
  • Punjabi New!
  • Romanian New!
  • Russian
  • Sanskrit New!
  • Serbian New!
  • Sindhi New!
  • Sinhalese New!
  • Slovak New!
  • Slovenian New!
  • Spanish
  • Swahili New!
  • Swedish New!
  • Tajik New!
  • Tamil New!
  • Tagalog New!
  • Telugu New!
  • Thai New!
  • Tibetan New!
  • Turkish New!
  • Ukranian New!
  • Urdu New!
  • Uzbek New!
  • Uighur New!
  • Vietnamese New!

Supported Language Translation Pairs

The Google AJAX Language API currently detects all languages listed above. A subset of those languages are translatable and are listed below. Any two languages from the following list can be translated. To test if a language is translatable, utilize google.language.isTranslatable(languageCode);

  • Arabic
  • Bulgarian New!
  • Chinese (Simplified and Traditional)
  • Croatian New!
  • Czech New!
  • Danish New!
  • Dutch
  • English
  • Finnish New!
  • French
  • German
  • Greek
  • Hindi New!
  • Italian
  • Japanese
  • Korean
  • Norwegian New!
  • Polish New!
  • Portuguese
  • Romanian New!
  • Russian
  • Spanish
  • Swedish New!

Flash and other Non-Javascript EnvironmentsNew!

For Flash developers, and those developers that have a need to access the AJAX Language API from other Non-Javascript environments, the API exposes a simple RESTful interface. In all cases, the method supported is GET and the response format is a JSON encoded result with embedded status codes. Applications that use this interface must abide by all existing terms of use. An area to pay special attention to relates to correctly identifying yourself in your requests. Applications MUST always include a valid and accurate http referer header in their requests. In addition, we ask, but do not require, that each request contains a valid API Key. By providing a key, your application provides us with a secondary identification mechanism that is useful should we need to contact you in order to correct any problems.

The easiest way to start learning about this interface is to try it out... Using the command line tool curl or wget execute the following command:

curl -e http://www.my-ajax-site.com \
'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=hello%20world&langpair=en%7Cit'

This command performs a Language Translation(/ajax/services/language/translate), for Hello World (q=hello%20world) from English to Italian (langpair=en%7Cit). The response has a Content-Type of text/javascript; charset=utf-8. You can see from the response below that the responseData is identical to the properties described in the Result Objects documentation.

{"responseData": {
"translatedText":"Ciao mondo"
},
"responseDetails": null, "responseStatus": 200}

In addition to this response format, the protocol also supports a classic JSON-P style callback which is triggered by specifying a callback argument. When this argument is present the json object is delivered as an argument to the specified callback.

callbackFunction(
{"responseData": {
"translatedText":"Ciao mondo"
},
"responseDetails": null, "responseStatus": 200})

And finally, the protocol supports a callback and context argument. When these url arguments are specified, the response is encoded as a direct Javascript call with a signature of: callback(context, result, status, details, unused). Note the slight difference in the following command and response.

curl -e http://www.my-ajax-site.com \
'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=hello%20world&langpair=en%7Cit&callback=foo&context=bar'

This command performs a Language Translate and is identical to the previous call, BUT has been altered to pass both callback and context. With these arguments in place, instead of a JSON object being returned, a Javascript call is returned in the response and the JSON object is passed via the result parameter.

foo('bar', {"translatedText":"Ciao mondo"}, 200, null)

curtsy: http://code.google.com

Monday

Andreessen: PHP succeeding where Java isn't

The simplicity of scripting language PHP means it will be more popular than Java for building Web-based applications, Internet browser pioneer Marc Andreessen predicted Wednesday in a speech here at the Zend/PHP Conference.

Java enjoyed great success when its inventor, Sun Microsystems, released it in 1995, largely because it was optimized better for programmers than for machines, making software development significantly easier, Andreessen said. Unfortunately, Java has acquired many of the unfavorable characteristics of its predecessors, he added.

Click here to view photo gallery

"Java is much more programmer-friendly than C or C++, or was for a few years there until they made just as complicated. It's become arguably even harder to learn than C++," Andreessen said. And the mantle of simplicity is being passed on: "PHP is such is an easier environment to develop in than Java."

That opinion might not sit well with Java loyalists--and there are plenty of them among the millions of Java programmers and hundreds of companies involved in the Java Community Process that controls the software's destiny.

But even some influential executives at IBM, which was instrumental in bringing Java to the server and whose WebSphere server software has Java at its core, see the benefits of PHP over Java.

"Simplicity is a huge part of it," said Rod Smith, vice president of IBM's Emerging Internet Technologies Group, describing PHP's appeal to IBM in a meeting with reporters at the conference. "They weren't interested in adding language features to compete with other languages," choosing instead "the simple way, and not the way we've done it in Java, unfortunately."

PHP is an open-source project including an engine to simple programs called PHP scripts and a large library of pre-built scripts. Much of its development is in the hands of a company called Zend, which sells packaged PHP products, programming tools and support.

Wooing programmers is nothing new in the computing industry, where players constantly jockey to establish their products as an essential foundation. Indeed, many credit Microsoft's success to its highly regarded programming tools, which make it easier for developers to write software that run on Windows.

"Java and PHP compete at some level. Get over it."
--Mike Milinkovich,
executive director,
Eclipse

PHP has caught on widely. About 22 million Web sites employ it, and usage is steadily increasing. About 450 programmers have privileges to approve changes to the software. Major companies that employ PHP include Yahoo, Lufthansa and Deutsche Telekom's T-Online.

PHP is more limited in scope than Java, which runs not just on Web servers but also on PCs, mobile phones, chip-enabled debit cards and many other devices. Some parts of the Java technology, though, such as Java Server Pages, handle much the same function.

"Java and PHP compete at some level. Get over it," Mike Milinkovich, executive director of Eclipse, said in a meeting with reporters. Eclipse is an open-source programming-tool project that long supported Java and now also supports PHP. "I'm looking forward to PHP kicking butt in the marketplace," Milinkovich said.

Java and PHP are drawing nearer to one another, though. Oracle, which also sells Java server software and whose database software can be used as a foundation for either Java or PHP, is among those working on an addition to Java to help the two software projects work together. Specifically, Java Specification Request 223 will "help build that bridge between the Java community and the PHP community," said Ken Jacobs, vice president of product strategy at Oracle, in a speech at the conference.

And even Andreessen, who just helped launch a start-up called Ning for sharing photos, reviews or other content online, acknowledges that Java has its place.

"My new company is running a combination of Java and PHP. This is something I get no end of crap about," he said of the technical decision. "We have a core to our system that is built in Java. It is more like an operating system, like a system programming project. Then we have the entire application level--practically everything you see is in PHP."

PHP, like open-source projects including Linux and Apache, now has received the blessing of major powers in the computing industry. IBM and Oracle are working on software that let PHP-powered applications pull information from their databases, and that endorsement has been important, said Zend CEO Doron Gerstel.

"The fact that IBM and Oracle are behind it--this is for a lot of IT (customers) a quality stamp. The big guys endorse it, so it must be good," Gerstel said in a meeting with reporters.

The new version 5.1 of PHP, scheduled to arrive in early November, will include a faster engine to process PHP scripts, said Zeev Suraski, a Zend co-founder and PHP creator. It also will include a low-level "data abstraction layer" that makes it easier for PHP to communicate with different databases and a higher-level layer to interface with XML information produced and consumed by Web services.

"They got mad. Then I told them we wanted to name it JavaScript, and that made them even madder."
--Marc Andreessen,
founder, Netscape

Version 6, which is expected to arrive in 2006, will support Unicode character encoding, which supports a wide range of alphabets, simplifying creation of software that works in multiple international regions.

Andreessen said he believes the Web is where most new applications will reside--in part because Web applications are available as soon as they're launched, sidestepping the distribution challenge of desktop software.

"Microsoft talks a lot about Avalon (display technology in the upcoming Vista version of Windows) and fat clients. But they still have a problem. You have to get the program out onto everybody's desktop. With the Web model, you don't," Andreessen said. "I think there's no question the Web model is going to dominate over the next 10, 20, 30 years."

Some interesting work is being done on the PCs, however, but he pointed only to applications that run in a Web browser and that rely on data and services supplied over the Internet. Here, again, Java is losing to an unrelated scripting technology called JavaScript and a JavaScript offshoot called AJAX that permits a fancier user interface.

"JavaScript was, and now with AJAX is, the standard way to do client-side development in a browser, as opposed to Java," Andreessen said. "Java applets in the browser never took to the extent some of us thought they would."

Not everyone sees things the same way. Google uses some cutting-edge browser-based software such as AJAX, but CEO Eric Schmidt took the stage earlier this week with Sun CEO Scott McNealy to announce that the Google Toolbar will be piggybacking on distributions of the desktop version of Java.

"I was amazed to find out how much the Java Runtime Environment is inside companies, either because a CIO standardized on it or there are enough applications that the CIO wants the JRE to be a standard" part of the company's computing infrastructure, Schmidt said at the Sun-Google event. As part of that partnership, Google will help develop Java.

Netscape pushed JavaScript as a way to build fancier Web pages than the fundamental HTML (Hypertext Markup Language) standard permitted, but without the more difficult programming Java required, Andreessen said. "We did JavaScript to try to be an intermediate bridge between HTML and Java. I got in huge fights with Sun over this," Andreessen said. "They got mad. Then I told them we wanted to name it JavaScript, and that made them even madder."

Java isn't the only client software that didn't live up to its promise, Andreessen said. Macromedia's Flash format, which enables animation, sound, motion and other splashy features within browsers, also is on the list.

"I think Flash is one of the most exciting technologies out there that's almost on the verge of great success and never quite achieving it," Andreessen said
curtsy:http://news.cnet.com

Beyond Spot-Checking: Why LLM Applications Require Specialized Evaluation

  images generated by meta ai Building applications with Large Language Models (LLMs) feels deceptively fast at first. A single engineer can...