Category Archives: JavaScript

PHP function to output flot data from a SQL query

In the hopes that other find this useful, here’s a concise function that assumes the first field is foor the date and names date, the rest are multiple series in a chart. Edit to suit.

function sql2Flot($sql){
$result  = mysql_query($sql);
//Data for FLOT =  [ {data:[[x,y]],label:”str”} ]
//row loop
$arrData = array();
$y=0;
while ($row = mysql_fetch_assoc($result)){
//field loop
$x=0;
foreach($row as $name=>$value){
//create the different series. assumes the first col is x, the rest are diff y series
$intDate = date(‘U’,strtotime($row['date']))*1000;
if($y==0 & $x>0){array_push($arrData,array(“label”=>$name,”data”=>array()));}
if($x>0){array_push($arrData[$x-1]['data'], array($intDate,$value));}
$x++;
}
$y++;
}
return json_encode($arrData);
}

more jqGrid patterns

I have been using jqGrid a lot, and thought I’d post a few of the solutions / hacks I came up with that were useful:

/* replace grid values */
    ,loadComplete: function(){
        var ids = jQuery("#grid").getDataIDs();
        /* for each row loaded */
        for(var i=0;i<ids.length;i++){
            var cl = ids[i];
            /* get the row data, this works best when you have to do this for multiple columns, otherwise you might use getCell  */
            var objRowData = jQuery("#grid").getRowData(cl);
            /* for each column, give it a replacement or function that modifies the value */
            jQuery("#grid").setRowData(cl,{
                ntlm:renderCheckmark(objRowData.ntlmHidden)
            });
        }
    }

/* Allow resort of rows. */    
    ,loadComplete: function() {
        jQuery("#grid").tableDnD({
            onDrop:function(objTable,objRow) {
                /* get the resulting order */
                var rows = jQuery(‘#grid’).getDataIDs();
            }
        }
    }
   
/* Add something in the middle of the navbar where the inserted position is relative to the "eq(1)" */
jQuery(‘#gridPager td.nav-button:eq(1)’).after(‘html stuff to add in’);

/* Use the nav bar for buttons but hide the pager. CSS */
#grid  #first, #grid  #prev, #grid  input.selbox, #grid  #sp_1, #grid  #sp_2, #grid  #next, #grid  #last{display:none;}
 

Only show the pager when there are enough rows to use it.

,loadComplete: function(){
        /* Dynamically show the pager if it’s needed */
        if(jQuery("#tableGroup").getGridParam("records") > jQuery("#tableGroup").getGridParam("rowNum")){
            jQuery(‘#tableGroupPager’).find(‘#first, #prev, input.selbox, #sp_1, #sp_2, #next, #last’).show();
        }else{
            jQuery(‘#tableGroupPager’).find(‘#first, #prev, input.selbox, #sp_1, #sp_2, #next, #last’).hide();
}
}
 

Scrolling a large table with Fixed Horizontal and Vertical Headers

This was a fun little solution I thought was worthy of sharing.

The Problem: You have a  very large grid. you need to display it on one page, but when you scroll you loose sight of the headers.

The solutions: Create separate tables for the headers, put them in containers that hide the overflow, and use slidersto control the scrolling.

Demo: http://anthong.com/examples/scrollxy/

References: http://demos.flesler.com/jquery/scrollTo/  http://docs.jquery.com/UI/Slider

Enjoy,

-Anthony

eyeOS: More than another framework.

I have been working with eyeOS lately. I hacked around with some of the existing components, and developed one of my own. I can tell you that after researching every “Web Desktop” and “Virtual Desktop” I could find reference to, this is the best one that you can download and manipulate under an open source license. This project is unique in its approach. They have merged the use of PHP with javascript to seamlessly complement each other and create an actual OS on a web platform. One thing I noticed right away as I started developing with it, is that this team concentrated on creating systems that would be beneficial to having a web environment rather than a bunch of web apps throw together. For example, each running module or “eyeApp” is assigned a serialized process ID which can be used to kill the process, or Identify it. There is a lot of work that needs to be done on it depending on your application for it. The windowing system is done very well but all of the eye candy is not as rich as something like extjs. The PHP is clean and very innovative, but there are many core features that it lacks (Like native DB support). Since I started working with it, I have run across many more projects that are in the same area and I’m still very happy that I chose to go through the learning curve on this one. Here is a summary review to compare with other products: 0-10 style

  1. Cost: Free (Under an Open Source License)
  2. Features: 7
  3. Presentation: 8
  4. Code maturity: 8
  5. Documentation: 4
  6. Community:8
  7. User learning curve: 30 minutes
  8. Developer Learning curve: 3 days

If you have huge $$ to blow and want a commercial product to invest in instead of spending development time customizing eyeOS I recommend checking out the Laszlo webtop.

MooTools js toolkit review.

I have just completed a project using Mootools exclusively for the javascript.

SELECTORS:

I found the $ and $$ selectors to be extremely useful. The $selector will return a single object based off of a name. The $$ selector will return an array of objects to work with based off of CSS selectors and more. The $$ function is where I found the most power because it allows you to collect a set of elements quickly, recurse through them and apply an action and repeat in very few lines. I used the $$ function to recurse through input elements and add a change event to them. I often had problems with the $$ selector selecting more elements than I wanted. It seemed to be using an “or” on my conditions when it said it would use an “and”. I was able to correct it by trying alternate selectors.

AJAX:

calls and handling are incredibly simple and powerful, but I had difficulty manipulating the return object without putting it in the DOM somewhere first.

DOCUMENTATION:

There is a lot of documentation for Mootools but I came to quickly find out that most of it is just a listing of method or property names, with very few examples. The examples that are provided are very useful. When I posted anything in the forums I got a fast and helpful response.

RECOMMENDATION:

I would recommend this framework to the javascript developer that is looking for a good set of utility libraries and is performance conscious, not an HTML developer that is looking for an easy way to add javascript to their page (For that I’d recommend Dojo). I’m working with jquery now, and I find a lot of the powerful features I appreciated in Mootools are also in jquery. I will write a little comparison between the 2 of them after I have used jquery as much as Mootools.

Javascript Error Logging

Javascript Error logging.

Upon investigation this is so incredibly simple I’m surprised it’s not done more often. any javascript error that occurs on a page can be gracefully handled and/or logged. It still makes sense to use a try/catch block for important functions so that you can handle errors at a more specific level. This serves as a good catch all.

W3Schools link

I think this information would be very useful to have and report from if you rely heavily on javascript in your pages. If you have a commonly occurring error you’ll know about it and be able to fix it and monitor the results. The opposite can be assumed as well. If you have a lot of connections from a certain browser / OS combination and you don’t see any errors from those session (Assuming the logging is working) you can assume with some evidence that those combinations are working.

What I did is gather all of the errors up in an XML string and send them through webRTAM so that I could associate it with the rest of the session info being logged.

webTRAM update

webTRAM is well on it’s way to being complete and stable product. Since I first posted about it, I redesigned and rewrote it, ading features and flexibility and performance. The code and demo have ben updated. The full working demo is included in the code so it will be pretty easy to get started.

 I have a few things I’ll be fixing and adding to it before I leave it alone for a while but all constructive and civil comments are welcome.

 http://SuddenDevelopment.com/?page_id=7

webTRAM demo updated.

demo link:  http://anthong.com/webTRAM/demo/

the demo has been upgraded significantly to inlude all of the latest features with some ways to demonstrate them.

Powered by ScribeFire.

Percent to RGB in Javascript

This is a small function I wrote today to take a value from 0-100 and return a color code in rgb(000,000,000) format. I use it to populate CSS values to color code elements based on a percent value. It could be used in mapping, charting, and grid views. Th colors points in the gradient are:

  • 0 = blue
  • 25 = green
  • 50 = yellow
  • 75 = orange
  • 100 = red
function percent2Color(intPercent)

{

 var intRed=0;intGreen=0;intBlue=0if (intPercent > 0 &amp;&amp; intPercent < 26)

 {

     intRed = 0;

     intGreen = (intPercent * 10.2);

     intBlue = 255(intPercent * 10.2);

 }

 if (intPercent > 25 &amp;&amp; intPercent < 51)

 {

     intPercent -= 25;

     intRed = (intPercent * 10.2);

     intGreen = 255;

     intBlue = 0;

 }

 if (intPercent > 50 &amp;&amp; intPercent < 101)

 {

     intPercent -= 50;

     intRed = 255;

     intGreen = 255(intPercent * 5.1);

     intBlue = 0;

 }

 intColorSum = intRed + intGreen + intBlue;

 (intColorSum > 380)? strFontColor = ‘#000000′: strFontColor = ‘#FFFFFF’;

 //alert(‘rgb(‘+Math.round(intRed)+’,'+Math.round(intGreen)+’,'+Math.round(intBlue)+’)');

 return ‘rgb(‘+Math.round(intRed)+‘,’+Math.round(intGreen)+‘,’+Math.round(intBlue)+‘);’;

}

More Intelligence in Popup Blocking Detection.

I found a lot of links that told me how to do popup blockers, most of them produced errors when you ran them but still worked at a basic level. Then I was given a requirement to dynamically detect popups everytime one is blocked, instead of just once when the page is loaded. This too k a more intelligent and universal solution.

What I came up with was a script that attaches the popup blocking detection to the onclick action of every link that has a target that starts with an underscore. This way you could simply include the script at the beginning of any file and it will deal with all of the links that meet this crietria.

Enjoy

//attaches the popup blocking function to all links that have a target starting with an underscore
function setUpAnchors()
{
var Anchors = document.getElementsByTagName(‘a’);<code>for (i = 0; i < Anchors.length; i++)
{
AnchorTarget = Anchors[i].target;

if (AnchorTarget.substr(0,1) == ‘_’)
{
Anchors[i].onclick = DetectPopupBlock;
}
}
}

//function to check if popups are blocked and take action if they are
function DetectPopupBlock()
{
var mine = window.open(,,‘width=1,height=1,left=0,top=0,scrollbars=no’);

if(mine)
{
var popUpsBlocked = false
mine.close()
}
else
 {
  //THIS IS WHERE YOU PUT YOUR ACTION IF POPUPS ARE BLOCKED.
  var popUpsBlocked = true   alert(‘Popups are blocked’)
 }
}
</code>

Page 1 of 212