Sunday, December 20, 2009

Articles Moving Back to Code Diaries

Hi All,

In the name of offering a more consistent service, all the articles under scriptdiaries.blogspot.com are now moving back to the main site codediaries.blogspot.com. This is to make it easier to maintain as I don't have the time to administer too many sites. While most articles have moved over. Some will take a little longer as I will edit them and make them better before I add them to code diaries.

Thanks,
Righteous.

Thursday, November 5, 2009

Lesson 4 - Advanced Twitter Widget Using Multiple Calls

This tutorial has moved back to Code Diaries.

You can view it there at Funky Twitter Thoughts Widget Using Yahoo and Twitter JSON APIs

Lesson 3 - Search Widget that Displays Images and Related Keywords

Summary
This is lesson 3 of 4. In this lesson we will use Yahoo's image search API to display images in a circle. We will then use Yahoo's "context" API to extract relevant keywords. This widget makes two seperate calles to the Yahoo API. This is done by loading itself into an "iframe" and then using the "parent" object like parent.callAFunction() to deliver the results. Back to the Lesson Index.


Explanation
First let us have a quick look at the code.









You can download a zipped version of all the lessons here


Back to the Lesson Index

Lesson 2 - Weather and News Widget Using RSS Reader

Summary
This is lesson 2 of 4. For this example we will use Google's RSS feed API to decode rss feeds and display them on a site. This widget will display weather taken from Yahoo's weather RSS feed and local news taken from two selected newspaper RSS feeds. View this Widget !!!


Explanation
First let us have a quick look at the code. First let's have a look at the weather.js file.
 1. /*      scriptdiaries.blogspot.com 
 2.         Righteous Ninja aka Ping Ching.
 3.         Free to use and modify.*/
 4.         
 5. google.load("feeds", "1");
 6. var YW_ContainerOk=false;
 7. function YW_GetWeatherResults(result){
 8.     if (!result.error){
 9.         s="<table  style=\"border-width:1px;border-collapse:collapse;border-style:solid; "+
10.             "border-color:#6D7B8D;width:1px;height:1px\" bgcolor=\"#ffffff\"><tbody><tr><td>"+
11.             result.feed.entries[0].content.match(/<img .*?>/)+"</td></tr></tbody></table>";
12.         document.getElementById("YW_weather_container").innerHTML="<b>"+result.feed.entries[0].title+
13.             "</b><br/>"+result.feed.entries[0].content.replace(/<img .*?>/,s);
14.     }
15. }
16. function YW_CallWeather(hrf){
17.     if(!YW_ContainerOk){
18.         document.write("<div id=\"YW_weather_container\">There is no weather information available "+
19.         " for this location at this time</div>");
20.         YW_ContainerOk=true;
21.     }
22.     (new google.feeds.Feed(hrf)).load(YW_GetWeatherResults);
23. }
Hide line numbers


Now let's have a look at the newsreader.js file
 1. /*      scriptdiaries.blogspot.com 
 2.         Righteous Ninja aka Ping Ching.
 3.         Free to use and modify.*/
 4.         
 5. google.load("feeds", "1");
 6. var NWS_ContainerOk = false;  
 7. function NWS_GetNewsResults(result){
 8.     if (!result.error){
 9.         for(i=0;i<result.feed.entries.length;i++){
10.             tmprs = result.feed.entries[i];
11.             document.getElementById("gansyman").innerHTML+="<a href=\""+tmprs.link+"\">"+
12.                 tmprs.title+"</a><br/>"+tmprs.content.substring(0,100)+"<br/>";
13.         }
14.     }
15.     else
16.         alert(result.error.message);
17. }
18. function NWS_CallNews(hrf, num){
19.     if(!NWS_ContainerOk){
20.         document.write("<div id=\"gansyman\"></div>");
21.         NWS_ContainerOk= true;
22.     }
23.     var feed = new google.feeds.Feed(hrf)
24.     feed.setNumEntries(num);
25.     feed.load(NWS_GetNewsResults);
26. }
Hide line numbers

Finally let us have a look at how you can embed this in an html page.
 1. <html>
 2.         <!--    
 3.         scriptdiaries.blogspot.com 
 4.         Righteous Ninja aka Ping Ching.
 5.         Free to use and modify.-->
 6. <head>
 7. <script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAA40MrnqI6U_ttOMK0wTpPSRQD6263AO_J-cN-o5MVlTXsf8kbcBRDZ3IoIMGa4lhUHoT28Z8OHamBhA"></script>
 8. <script type="text/javascript" src="weather.js"></script>
 9. <script type="text/javascript" src="newsreader.js"></script>
10. </head>
11. 
12. <body>
13. <h2>Weather</h2>
14. <table width="100%">
15.     <tbody>
16.     <tr>
17.         <td>
18.         <select onChange="YW_CallWeather(this.options[this.selectedIndex].value)">
19.             <option value="http://weather.yahooapis.com/forecastrss?p=CEXX0001&u=c">Colombo</option>
20.             <option value="http://weather.yahooapis.com/forecastrss?p=CEXX0002&u=c">Moratuwa</option>
21.             <option value="http://weather.yahooapis.com/forecastrss?p=CEXX0003&u=c">Negombo</option>
22.             <option value="http://weather.yahooapis.com/forecastrss?p=CEXX0004&u=c">Sri Jayawardenepura</option>
23.             <option value="http://weather.yahooapis.com/forecastrss?p=CEXX0005&u=c">Katunayake</option>
24.         </select>
25.         </td>
26.     </tr>
27.     <tr>
28.         <td>
29.             <script>
30.             YW_CallWeather("http://weather.yahooapis.com/forecastrss?p=CEXX0001&u=c");
31.             </script>
32.         </td>
33.     </tr>
34.     </tbody>
35. </table>
36. 
37. <h2>News</h2>
38. <script>
39. NWS_CallNews("http://www.dailymirror.lk/DM_BLOG/RSS/FrontPageRSS.xml",3);
40. NWS_CallNews("http://www.lankanewspapers.com/news/rss.xml",3);
41. </script>
42. 
43. </body>
44. </html>
Hide line numbers





You can download a zipped version of all the lessons here

Back to the Lesson Index

Lesson 1 - Sexy Widget That Displays a Sexy Quote and a Sexy Picture

Summary
This is lesson 1 of 4. It is the simplest form of widget possible. For this widget we will create some simple javascript that will randomly display an image and a quote. The images and quotes will be held in two arrays. The javascript Math.random function will be used to select an image. View this Widget !!!

Explanation
First let us have a quick look at the code. This is the simplest example so the code is very straigntforward.
 1. /*      scriptdiaries.blogspot.com 
 2.         Righteous Ninja aka Ping Ching.
 3.         Free to use and modify.*/
 4.         
 5. var SXY_cutegirls = new Array("http://codediaries.com/widgets/cutelnka/wid_cutelnka_anarkalli.jpg",
 6.                         "http://codediaries.com/widgets/cutelnka/wid_cutelnka_nadeeka.jpg",
 7.                         "http://codediaries.com/widgets/cutelnka/wid_cutelnka_derana.jpg");
 8. 
 9. var SXY_cutequotes = new Array(
10.     "Sex without love is an empty experience, but as empty experiences go, it's one of the best.",
11.     "Sex is not the answer. Sex is the question. Yes is the answer.",
12.     "Sex without love is an empty experience, but as empty experiences go, it's one of the best.",
13.     "The sex was so good that even the neighbors had a cigarette.",
14.     "The difference between pornography and erotica is lighting.",
15.     "Sex is like a bridge game; if you don't have a good partner, you better have a good hand."
16. );
17. 
18. function SXY_DoSexyWidget(){
19.     document.getElementById('cutelankapanel').innerHTML=
20.         "<center>"+
21.         "<img src=\""+SXY_cutegirls[Math.round((SXY_cutegirls.length-1)*Math.random())]+"\"/>"+
22.         "<br/>"+
23.         SXY_cutequotes[Math.round((SXY_cutequotes.length-1)*Math.random())]+
24.         "</center>";
25. }
Hide line numbers

Now let us look at how you would embed this in a web page
 1. <html>
 2.         <!--    
 3.         scriptdiaries.blogspot.com 
 4.         Righteous Ninja aka Ping Ching.
 5.         Free to use and modify.-->
 6. <head>
 7. 
 8. <style  TYPE="text/css">
 9. .cutelanka_quotes{font-family:arial;font-size:11px;color:#ffffff;}
10. </style>
11. 
12. <script type="text/javascript" src="sexywidget.js"></script>
13. 
14. </head>
15. <body>
16. 
17.     <table border="0" cellpadding="0" cellspacing="0" width="190px">
18.         <tbody>
19.             <tr><td background="frame_top.gif" height="10px"></td></tr>
20.             <tr><td bgcolor="#000000" class="cutelanka_quotes"><div id="cutelankapanel" width="100%"></div></td>
21.             </tr><tr><td background="frame_bottom.gif" height="10px"></td></tr>
22.         </tbody>
23.     </table>
24. <script>
25. SXY_DoSexyWidget();
26. </script>     
27. </body>
28. </html>
Hide line numbers


You can download a zipped version of all the lessons here

Back to the Lesson Index






You can download a zipped version of all the lessons here

Back to the Lesson Index

Sexy Random Image and Quote Widget



Learn more about this Widget
Super sexy widget that displays a random hot girl with a sexy and funny quote. Refresh page for a different quote and image. This can be easily changed to include any images and any number of quotes. Pure javascript only.

Wednesday, November 4, 2009

News and Weather Widget - Sri Lanka


Sri Lanka Weather




Sri Lanka News


Learn more about this widget
A RSS feed widget that displays the news and weather in Sri Lanka. This uses Google's feed API, Yahoo's weather RSS feed and the feeds from two Sri Lankan Newspapers. This widget can be easily adapted to display news and weather from any country or a combination of countries.

What is on Kim Kardashians Mind? Twitter Thoughts Widget

Learn more about this widget
A twiter widget that displays what has been on Kim Kardashian's mind for the past week. This widget can be easily adapted to display any celebrity or entity on twittter.

Sunday, November 1, 2009

What is on Paris Hilton's Mind? Twitter Thoughts Widget



Learn more about this widget
A twiter widget that displays what has been on Paris Hilton's mind for the past week. This widget can be easily adapted to display any celebrity or entity on Twittter. Pure Javascript only. Using Twitter and Yahoo APIs.

Wednesday, October 21, 2009

Free APIs That You Can use To Create Your Widget

There are heaps and heaps of free APIs on the web that you can use to mash up and create a widget. Most of the giants such as yahoo, google, twitter, digg etc have APIs that allow you to leverage off their search and social networking engines. Here we will list only the big names, but there are thousands of equally if not better services offered by smaller players for free.

Welcome to Do It Yourself Widgets

This article has moved back to Code Diaries,

You can find it at Learn How to Crete Pure Javascript Widgets

Tuesday, October 20, 2009

Moving, Hiding and Writing to a Layer in Javascript

This article has moved back to Code Diaries.

You can find it at Moving, Hiding and Writing to a Layer in Javascript

Wednesday, October 14, 2009

Increase Widget Font Size in Blogger(Blogspot)

If you would like to simply icrease the font size in the widget content without installing other widgets or embedding fancy javascript, you can edit the size in the template. Go to the Dashboard, click on Layout and select Edit HTML. Now look for the text below.

 1. .widget-content { 
 2.   margin-top: 0.5em;
 3. }
Hide line numbers

You can modify this to increase the size, font, color etc of the widget content like so.
 1. .widget-content { 
 2.   margin-top: 0.5em;
 3.   font-size:110%; 
 4.   color:#FF6600;
 5. }
Hide line numbers

Tuesday, October 13, 2009

Remove the Blogger(Blogspot) Navi Bar/Banner at the Top

If you want to remove the Blogger bar at the top because it's clashing with your site. Many people seem to think this is illegal, that is up to you to decide. Go to the Dashboard. Click on Layout and then click "Edit HTML". Now stick this bit of code somewhere.

#navbar-iframe {
display: none;
}

Easiest is just before the "body {" and after the variable definitions. So your template should have this bit of code in it like below.
 1.    <Variable name="endSide" description="End side in blog language"
 2.              type="automatic" default="right" value="right">
 3. */
 4. 
 5. 
 6. #navbar-iframe {
 7.    display: none;
 8. }
 9. 
10. 
11. body {
12.   margin:0px;
13.   padding:0px;
Hide line numbers

Web 2 Tips and Tricks


Helpful hints when creating web 2 widgets, writing perl code or setting up a page to use php or ssi. Hint's and tips you would not find anywhere else.

Javascript Need to Know

Everything you need to know about javascript. DOM, XML, AJAX. With the basics outlined in the following tutorials, you could make the richest and most inreactive site or widget.

Asynchronous Javascript and XML (AJAX) Example
Creating a Class in Javascript
Getting URL "GET" parameters using Javascript

Monday, October 12, 2009

Creating a Class in Perl

This article has moved back to Code Diaries.

You can view it there at Creating a Class in Perl

Friday, October 9, 2009

Creating a Class in Javascript

This article has moved back to Code Diaries.

You can find it there at Creating a Class in Javascript

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.