Wednesday, September 30, 2009

Javascript Asynchronous XML Example (AJAX)

This is a simple AJAX tutorial using php, javascript and XMLHttpRequest. AJAX is the fundamental lynchpin of web 2 services and underpins almost every widget today. This is the simplest example that demonstrates AJAX.

This example consists of two files. ajaxexample.html contains all the javascript and getresult.php is the php backend that returns an xml result. Create or copy these two files into the same directory on a webserver (such as apache) that supports php.

ajaxexample.html
 1. <html>
 2. <head>
 3. <script language="javascript">
 4. function new_XHR() {
 5.     var xhr;
 6.     try{
 7.         xhr = new ActiveXObject("Msxml2.XMLHTTP");
 8.     }catch(e){
 9.     try{
10.         xhr = new ActiveXObject("Microsoft.XMLHTTP");
11.         }catch(E){
12.             xhr = false;
13.         }
14.     }
15.     if(!xhr && typeof XMLHttpRequest != 'undefined'){
16.         xhr = new XMLHttpRequest();
17.     }
18.     return xhr;
19. }
20. 
21. var myxhr;
22. function DoAjaxCall(){
23.       myxhr = new_XHR();
24.       myxhr.onreadystatechange=MyAjaxCallback;
25.       myxhr.open('GET',"getresult.php?"
26.         +"name="+document.getElementById("NameBox").value);
27.       myxhr.send(null);
28.     }
29.        
30. function MyAjaxCallback(){
31.     var name;
32.     var message;
33.     if(myxhr.readyState==4 && myxhr.status==200){
34.         var subrootNode = myxhr.responseXML.getElementsByTagName('user-data');
35.         for(i = 0 ; i < subrootNode[0].childNodes.length ; i++){
36.             var node = subrootNode[0].childNodes[i];
37.             if(node.tagName=="name")
38.                 name=node.firstChild.nodeValue;
39.             else if(node.tagName=="message")
40.                 message=node.firstChild.nodeValue;
41.             else{}
42.         }
43.         document.getElementById("MessagePane").innerHTML = 
44.                                     "<b>"+name+" :</b> \""+message+"\""; 
45.     }
46. }
47. </script>
48. </head>
49. <body>
50. <form>
51. Name <input id="NameBox" type="text"/>
52. <a href="javascript:DoAjaxCall()">Send the data without submitting the form</a>
53. </form>
54. <div id="MessagePane"/>
55. </body>
56. </html>
Hide line numbers
Now type http://127.0.0.1/WEB/AJAXExample/ajaxexample.html in a browser, type your name in the textbox and click on the link.

lines 4-19 Creates an XMLHttpRequest object

lines 22-28 DoAjaxCall get's called when you click on the link. This creates an XMLHttpRequest object sets MyAjaxCallback as the callback function and adds the url to call.

lines 30-46 Once getresult.php is called the MyAjaxCallback function is called with the reuslt. You can then 'decode' the XMLHttpRequest object by traversing the sctructure and extracting the information.

getresutl.php
 1. <?php header('Content-type: text/xml');
 2.  
 3. $my_name = $_GET["name"];
 4. 
 5. $dom = new DomDocument('1.0');
 6. $dom->formatOutput = true;
 7. 
 8. $userdata = $dom->createElement( "user-data" );
 9. $dom->appendChild( $userdata );
10. 
11. $name = $dom->createElement("name");
12. $name->appendChild($dom->createTextNode("Doctor Octopus"));
13. $userdata->appendChild($name);
14. 
15. $mesg = $dom->createElement("message");
16. $mesg->appendChild($dom->createTextNode("Hello there $my_name, prepare to be mangled"));
17. $userdata->appendChild($mesg);
18. 
19. echo $dom->saveXml();
20. 
21. ?>
Hide line numbers
You can call this php script directly by typeing http://127.0.0.1/WEB/AJAXExample/getresult.php?name=sheena in your browser

Tuesday, September 22, 2009

PHP Database Example - MySQL

This is a simple php Database example illustrating the basics such as creating an SQL query, fetching and updating a database. For this example we will be using a MySQL Database. However, this will work with any database. This example will use commands such as mysql_connect, mysql_fetch_object, mysql_query etc.

First lets have a look at the example. It's self explanatory.
 1. <?php
 2. try{
 3.     mysql_connect("localhost", "user1", "pwd");
 4.     mysql_select_db("mydatabase");
 5. }catch(Exception $e){
 6.     echo mysql_error();
 7.     exit;
 8. }
 9. /*Select*/
10. $result = mysql_query('select * from user_table');
11. 
12. while($row = mysql_fetch_object($result)) {
13.   echo "$row->id $row->first_name $row->address\n"; 
14. }
15. 
16. /*Update*/
17. $result=mysql_query("update user_table set first_name='barbie' where id=100");
18. 
19. mysql_close();
20. 
21. ?>
Hide line numbers

PHP DOM XML Example - Document Object Model

This is a simple php 5, DOM/XML example illustrating the basics such as creating tags, name/vaule pairs and text nodes using createElement, appendChild , setAttribute etc. The XML is displayed on the console, but could just as well be the response to an XMLHttpRequest.

First lets have a look at the example. It's self explanatory.
 1. <?php 
 2. 
 3. $dom = new DomDocument('1.0');
 4. $dom->formatOutput = true;
 5. 
 6. $carroot = $dom->createElement("car-root");
 7. $dom->appendChild($carroot);
 8. 
 9. $car = $dom->createElement("car");
10. $car->setAttribute("model","Ferrari F60");
11. $carroot->appendChild($car);
12. 
13. $description = $dom->createElement("description");
14. $description->appendChild($dom->createTextNode("Enzo Ferrari"));
15. $car->appendChild($description);
16. 
17. $engine = $dom->createElement("engine");
18. $engine->appendChild($dom->createTextNode("V12"));
19. $car->appendChild($engine);
20. 
21. echo $dom->saveXml();
22. ?>
Hide line numbers

Monday, September 21, 2009

Javascript - Get URL Parameters from Form Submit

This article has moved back to Code Diaries

You can find it here Javascript - Get URL Parameters from Form Submit

Wednesday, September 16, 2009

Perl Basics - What You Really Need To Know

Once you know how to read from and write to a file, connect to a database and insert and retrieve records, use regular expressions  and open a socket to a server and read and write data, you have covered 80% of what is really required to write most applications in perl.

Perl Socket Example
Perl File Example
Perl Database Example
Perl Regular Expression Example

Creating a class in Perl

Perl File Example

The aim of this simple example is to show how to read and write a file in Perl. This will read from a file trim the white space at the start and end and append the result to another file.

First lets have a look at the example. It's really self explanatory.
 1. open (readfile, '<input.csv') or die "could not open file to read";
 2. open (writefile, '>>output.csv') or die "could not open file to write";
 3. while(<readfile>){
 4.     #read from 'readfile', trim and write to 'writefile'
 5.     $_ =~ s/(^ *| *$)//gi ;
 6.     print writefile $_;
 7. }
 8. close(readfile);
 9. close(sritefile);
Hide line numbers

Perl Database Example - ODBC DSN

This article has moved back to Code Diaries.

You can read this at Perl Database Example - ODBC DSN

Sunday, September 6, 2009

How to Write a Simple Web and Image Crawler in Perl

This article has moved back to Code Diaries.

You can read it at How to Write a Simple Web and Image Crawler in Perl

Perl Socket Example

The aim of this tutorial is to show how to read and write a socket in Perl. We will open a socket to a website, write the request headers, read the response and write the response to the console. You do not need any prior HTTP 1.x knowledge.

First lets have a look at the example. It's really self explanatory.
 1.     use IO::Socket;
 2. 
 3.     my $sock = new IO::Socket::INET (PeerAddr => 'localhost',
 4.                                         PeerPort => 8080, 
 5.                                         Proto => 'tcp');
 6.     die "could not create socket: $!\n" unless $sock;                                        
 7.     
 8.     printf $sock ("GET / HTTP/1.0\n");
 9.     printf $sock ("Host: localhost\n");
10.     printf $sock ("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
11.     printf $sock ("User-Agent: Mozilla/5\n");
12.     printf $sock ("Connection: keepalive\n");
13.     printf $sock ("\n\n");
14.     
15.     while (<$sock>) {
16.         if($_=~ m/validate_response/i) {
17.              last;
18.         }
19.          else{
20.              print $_;
21.         }
22.     }
Hide line numbers


Line 3 We open the socket to localhost on port 8080. This is where my server tomcat ususally runs. But you can change this to anything

Lines 8-13 Here we write out the reust HEADER to the webserver. Just remember if you change your host from 'localhost' to something else, you need to change line 9 to reflect that too.

Lines 15-22 Read the response from the webserver and write it to the screen.