Why Not?

What shall we do today…

Making jQuery calls in a function when a parameter can be a string or integer

Consider a function of when you are creating a list of items that have unique IDs, some are long integers and some are strings since they are a mix of chars and integers.  Also, you have very little control over these id values since they are retrieved from a web service and are too long and tedious to manually code.  Doesn’t sound too hard of a situation to code, but it is unique enough to where a large amount of searching will occur until a solution is found.

Lets assume we have an unordered list whose <li> elements had id values are a mix between integers and strings.  We also have a remove function to remove these <li> tags from the list:

<ul>
    <li id="1234">
        <a href="#" onclick="remove( 1234 )" ></a>
    </li>
    <li id="abc1234">
        <a href="#" onclick="remove( abc1234 )" ></a>
    </li>
</ul>

And the javascript function:

function remove( listID )
{
    if ( listID === parseInt( listID ) )
        $( "#" + listID ).remove();
    else
        $( "#" + listID.id).remove();
}

In this remove function, since we are dealing with two different types being passed into funciton, we must first determine if it is a string or integer.  If it is an integer, just go ahead and use the parameter passed in as is:

if ( listID === parseInt( listID ) )
    $( "#" + listID ).remove();

But if the parameter is a string, we must first get its ID property to retrieve the value being passed into the function so that we can make the jQuery call:

$( "#" + listID.id)

PHP – array_search() and boolean false

Yesterday while programming I came across a situation where I had to check if an array in php contained a value. Simple enough. Calling the

array_search

function does the trick. However, there is a small detail that involves this function, it returns the KEY of where in the array the value is located, if not it returns false. No problem if you are searching for said key, but I just wanted to check if the array simply contained the value i was searching for and php does not have a native function that would return just a true/false boolean. Not that big of a problem though since array_search() still does the trick.

Now using array_search, we can find whether or not an array contains a value:

—————————————————————————-

$haystack = array( "red", "blue", "green", "yellow");

array_search( "blue", $haystack ); //returns 1

array_search( "pink", $haystack ); //returns false

—————————————————————————-

Simple. But now look at this code:

—————————————————————————-

$haystack = array( "red", "blue", "green", "yellow");

array_search( "red", $haystack ); //returns 0

if( array_search( "red", $haystack ) != false )
{
          echo "We found red!";
}
else
          echo "nothing here";

—————————————————————————-

Now this code looks fine and dandy and should work to the normal eye, but it doesn’t. Going back to the original function or array_search(), with

array_search( "red", $haystack );

, it will return 0, which also evaluates to false in boolean logic, which makes our if statement fail.

The fix? use !== to verify that the return value of array_search() is false and is a boolean type.

This allows our original code to work as expected, and thus give us a pseudo boolean check if an array contains a value in php:

—————————————————————————-

$haystack = array( "red", "blue", "green", "yellow");

array_search( "red", $haystack ); //returns 0

if( array_search( "red", $haystack ) !== false )
{
          echo "We found red!";
}
else
          echo "nothing here";

—————————————————————————-

Please note, array_search() can return 0 and “”, which are FALSY values

Eclipse Ganymede and Rational Team Concert Released….on June 25

I know it is late, but Eclipse Ganymede was released the other week. Great job and thanks to all the developers across all of the projects within the Eclipse Foundation!

Get Eclipse Ganymede

Also released was IBM’s first product in its Jazz technology: Rational Team Concert. Certainly an interesting and great product that uses the newest in today’s technologies to allow developers across the world collaborate on their projects. It is built on top of Eclipse, so if you are familiar with that product you will be comfortable in the RTC IDE. My favorite thing about it? You can set up and play with this enterprise level product within 5 minutes.

Again, great job to the team of developers that worked to make this product reach its first release!

Check out Jazz

Chaining in jQuery

I just finished watching a great presentation by John Resig, creator of jQuery, on javascript and jQuery (redundant, i know). One interesting point he made about the library was the idea of chaining in jQuery and how it creates its own stack.

Given the following code:

$("ul").find("li").hide().end().find("div").load( "somePage.html" ).end();

Can translate into this:

$("ul") //returns [ul, ul, ul]
    .find("li") //returns [li, li, li]
        .hide() //hide all the li tags within the ul
    .end() //returns [ul, ul ,ul]

    .find("div") //returns [div, div]
        .load( "somePage.html" ) //ajax call to load html into some divs
.end(); //returns [ul, ul ,ul]

This feature of the library allows developers to write more “one-liner” code to save space and time. The interesting thing with this is that it creates its own stack to traverse through, always referencing the first object in the stack. These objects then exist until the .end() function is called, at which point the object is then removed from the stack and the previous object is currently referenced.

Taking this into note, what is occurring in my code is:

1. First grab all the ul elements in the page.

2. Now grab all the li elements within the ul elements and hide() them from the view

3. Go back to the original array of ul elements

4. Now lets grab all the div elements within the ul elements and call some ajax

5. Again, lets go back to the ul elements and end this craziness;

Granted, this example code is not the best to implement chaining to as it can promote difficult code maintainability and confusion when others read your code, but it is pretty useful and promotes the idea behind jQuery: Do more, write less.

My 5 minutes of fame

So back in March I was asked to give a tech talk on my experiences with IBM’s new product Rational Team Concert and its Jazz Platform. One of my colleagues mentioned that I was going to be mentioned in a press release, but I never saw it.

……until now.

IBM Helps Universities Prepare Future Software Leaders for Globalization

From the article:

On April 2, 2008 at Virginia Tech, Jazz will be featured in a lecture sponsored by the Association for Computing Machinery (ACM). The local ACM student chapter serves as a node of activity for people who share a common interest in computers. Fellow Virginia Tech student and IBM co-op John Ryding will share his experiences working with IBM on the development of the Jazz technology platform and its uses within a large globally integrated enterprise, like IBM, as well as how Jazz technology can be applied to educational advancement and student research.

Nice!

How to Submit Javascript Arrays through jQuery AJAX calls

When making ajax calls in jQuery there are 4 simple functions one can use to access data on the server:

$.ajax

$.get

$.post

$(‘#blah’).load

Now there is ample documentation about how to use these functions, but I have not seen any that deals with submiting data to the server from an array of values, which would make somehting like sending a list or marked checkboxes a lot easier.

To submit an array of values to the server with the $.ajax function one should do the following:


var query_string = '';
$("someElement").each(
function()
{
if (this.checked)
{
query_string += "&test[]=" + this.value;
}
});

$.ajax(
{
type: "POST",
url: "test.php",
data: "id=1" + query_string,
success:
function(t)
{
$("div#content").empty().append(t);
},
error:
function()
{
$("div#content").append("An error occured during processing");
}
});

Now what is occurring in this code is that we are first making a string of session variables with the “queryString” variable that will be appended to the URL of the $.ajax call. In the $.ajax function, one usually passes a string for the data input to be passed to the server.

The $.ajax call is not that bad and is very versatile, but to abstract things a little more we would use $.post, $.get, or .load. These three functions are used to, respectively, post and get data from the server, or to load data from the server once an event occurs with an element.

The documentation for these functions can be found here: jQuery Ajax Functions

The parameter we are most interested in with this functions is the “data” parameter. To pass an array through these functions we should do the following:


var inputArray = [];

$("#listOfData").each( function(){
inputArray.push( this.value )
})

$.post( "yourServerPage.php", { 'data[]': inputArray }, function( outputData ){
$("#outputDiv").empty().append( outputData );
});

Please note: The quotes around ‘data[]‘ as it tells the parameter to treat the values being submitted as an array. Also, the function that is passed as a parameter is completely optional.

Here is what function call would look like for $.get and .load:


$.get( "yourServerPage.php", { 'data[]': inputArray }, function( outputData ){
$("#outputDiv").empty().append( outputData );
});

$("#outputDiv").load( "yourServerPage.php", { 'data[]': inputArray }, function( outputData ){
//do stuff
});

This code was created with the help of the following:

http://jetlogs.org/2007/06/17/jquery-tutorial-passing-input-arrays/

http://groups.google.com/group/jquery-en/browse_thread/thread/011f91c665caa8a6

Retrieving the pixel location of a DOM element

jQuery is an awesome javascript library that GREATLY simplifies iterating through various elements in the DOM, retrieving various attributes of elements, and makes the amount of code you write smaller.

In this post I am going to explain a snippet of code that will grab the x and y pixel coordinates of any element in a web page one would need, independent of the browser, simply by searching for the id value of the element:

——————————————————————-
var coordinates;


$(document).ready(function() {
coordinates = $("#elementID").offset()
});

x = coordinates.left;
y = coordinates.top;

——————————————————————-

This snippet uses jQuery to run a function once the entire page has been loaded:

——————————————————————-

$(document).ready()

——————————————————————-

Then in the function we retrieve the CSS offset attribute of the DOM element we want by searching for:

——————————————————————-

$("#elementID").offset()

——————————————————————-

Note: $(“#elementID”) is a jQuery function that grabs the DOM element by searching for the given id value.

This line of code will then create an object with the following attributes, which give the pixel location of the corresponding sides of the element:

——————————————————————-
.top
.left
.right
.bottom

——————————————————————-

We are now able to retrieve the x-y pixel coordinates of any element on a web page independent of a user’s screen resolution or browser.

Toushcreen Turn Table

This is one of the coolest things I have ever seen.  A DJ turntable w/ touchscreens to “…allow DJs to play MP3s the same way they would play vinyl records.”  WOW. check out the link:

http://www.psfk.com/2008/05/attigo-tt-the-touch-screen-turntable.html

Seeqpod

So one of my friends recently showed me this website called seeqpod. The site is essentially a music search engine. You go to the site, type in a song or artist name, and boom results. What separates the site though, is its presentation and usefulness of its results. Essentially, a search results in seeqpod finding songs, videos, and articles of the song or artist you searched for, but these results are not just links. They are actually links to streams of what you searched for.

Basically, in your results, you can then click play and listen to the song or watch the video that was received right within seeqpod thanks to all of its AJAXiness. This seems useful to a point, woop dee do, i can do the same thing in last.fm WITH recommendations. What separates Seeqpod though, is that you can then create playlists of these streaming items.

For example, today at work I wanted to listen to some Guster on my iPod. Just as i went to press play, the battery died and I was too lazy to walk out to my car and grab a USB cord for the player. I still wanted my Guster fix (I am definitely hooked on “So Long”). So I went to Seeqpod, searched for Guster, and then created a playlist of all the songs I wanted to listen to. Fast forward an hour later, still listening to the same playlist I started off with. No having to deal with manually choosing each song. No random songs. Just easy to use, streaming music.

Using Gmail as a Spam Filter

Here is a problem: You have a website with email addresses and other people on a server. You are currently getting a boatload of spam and need a filter so taht you do not have to deal with 1000+ emails a day. The only thing is, you are unable to run a spam filter like Spam Assassin on your server because there are other websties and communities on the server. Running Spam Assassin will inhibit their software and websties and take up too much CPU power.

How do you solve this problem?

Use Gmail as your spam filter.

This is actually really easy to set up, the entire process is only a couple of steps. What you are essentially doing is having Gmail download all your messages from the server, use its spam filter, and then you download your messages from Gmail. You can also set up your email client to use another mail server for outgoing messages, so you NEVER have to dael with the unprofessional “On behalf of Gmail” tag in your email.

This tutorial assumes you are using Thunderbird as your email client, it can be downloaded from here

So here is how you do it:

1. Set up a Gmail account here

2. Now go to your Gmail inbox and click Settings in the top right

3. In the settings page click on Accounts

4. No in the accounts page, click on “Add another email Account” under “Get mail from other accounts”

5. In the window that pops up, type in the email address you wish to have gmail filter through and click Next

6. In the next window, type in your password, and check the boxes that you would like in the window.

**make sure that the box saying “Leave a copy of retrieved messages on the server” is UNCHECKED**

7. Click “Add Account”

8. Start Thunderbird and go to File > New > Account

9. Click the Gmail radio button

10. Give the account a name in the first box. In the second box type in the name you registered your Gmail account under.

11. Click on finish and make sure the checkbox next to “Download messages no” is checked

12. Click Finish

Your thunderbird client is now set up to download your filtered messages from your original server. Be aware that the account you just set up is configured to send mail through Gmail’s servers, so be sure to change that setting by right clicking on the account and clicking on Properties to chance the Outgoing Mail server.

Congratulations, you now have a low resource spam filter for your server.