May 5

jQuery, Selecting the Previous Element With Filtering

Recently I was looking for a solution to this problem. My HTML looked like this:

<a class="file" href="download/876243.pdf">876243.pdf</a>
<a class="tagcontrol" id="876243.pdf">tag</a>
<a class="tag" href="index.php?tag=test">test</a>
<img class="delete" title="remove this tag" src="img/tag-del.png" />
Here is how the tags will look.

Here is how the tags will look.

The idea being that you would click the image with the “delete” class and submit an ajax call to delete the tag for that file in a Folksonomy system. I had the hardest time trying to figure out how to select the tagcontrol link, I needed to acquire it’s ID for one of the data variables in the ajax call. The answer came from prevAll(). With only the “this” reference from the clicked image, you can find and select the most previous “a” element that has the “.tagcontrol” class.

This line allowed me to find only the most previous element that had the attribute of “a” anchor tag with a class of “tagcontrol”.

$(this).prevAll("a.tagcontrol").attr("id");

Here is the complete function:

$(".delete").live("click", function() {
    var thebutton = $(this);
    var todelete = $(this).prev().html();
    var file = $(this).prevAll("a.tagcontrol").attr("id");
    $.ajax({
        type: "GET",
        url: "tag.php",
        data: '?file=' + file + '&amp;delete=' + todelete,
        success: function(){
            thebutton.prev().remove();
            thebutton.remove();
        }
    });
    return false;
});

This came in handy for me using the search expression feature of the prevAll() function. It’s official purpose is “Find all sibling elements in front of the current element”. However that may be a little hard to understand. Hopefully my little demonstration will help you employ this feature of jQuery.

Apr 21

Start With Simplicity Itself

This startup knows what it’s doing.  Check out instantdropbox.com.  Probably the simplest user comment site ever, in fact, why don’t you use it to tell me what you think of my blog?

Mar 23

Tweet from the command line

Twitter is awesome, but who has time to fire up a browser, log in, type what you’re doing, just to be a part of the Twitter sensation?   If you spend more of your time on the command line, I’ll show you how to send your twitter messages using a simple bash script.

#!/bin/bash

user=twitteruser
pass=twitterpass
tweet=$1
curl -u ${user}:${pass} -d status=${tweet} http://twitter.com/statuses/update.xml

Save this bash script in your ~/bin directory and chmod 700.  Now you can tweet right from the command line.

tweet "Twitter is better from the command line"

If you’d rather not put your password in a text file (think multi-user systems) then, take out the “:${pass}” and curl will ask for it each time you run the “tweet” script.

Feb 21

File Uploads in a Hidden iframe using jQuery

I wanted to create a file uploading application in an Ajax style (that wouldn’t reload the page), but I found I didn’t like any of  the jQuery plugins that I found to do them.  I found that either they didn’t work or the result was not able to be styled the way I wanted.  Here is how I did using a hidden iframe to redirect the form attributes and upload the file with out reloading the host page.

Here is the HTML for the form:

<div id="uploadform">
<form id="theuploadform">
<input type="hidden" id="max" name="MAX_FILE_SIZE" value="5000000" >
<input id="userfile" name="userfile" size="50" type="file">
<input id="formsubmit" type="submit" value="Send File" >
</form>

The DIV in which to allow jQuery to create the iframe you can hide it with a little CSS:

<div id="iframe" style="width:0px; height:0px; visibility:none;">
</div>

The DIV in which to show the results of the callback:

<div id="textarea">
</div>

The jQuery code:

<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript">

$(document).ready(function(){
	$("#formsubmit").click(function() {
		var userFile = $('form#userfile').val();
		var max = $('form#max').val();
		var iframe = $( '<iframe name="postframe" id="postframe" class="hidden" src="about:none" />' );
		$('div#iframe').append( iframe );

		$('#theuploadform').attr( "action", "uploader.php" )
		$('#theuploadform').attr( "method", "post" )
		$('#theuploadform').attr( "userfile", userFile )
		$('#theuploadform').attr( "MAX_FILE_SIZE", max )
		$('#theuploadform').attr( "enctype", "multipart/form-data" )
		$('#theuploadform').attr( "encoding", "multipart/form-data" )
		$('#theuploadform').attr( "target", "postframe" )
		$('#theuploadform').submit();
		//need to get contents of the iframe
		$("#postframe").load(
			function(){
				iframeContents = $("iframe")[0].contentDocument.body.innerHTML;
				$("div#textarea").html(iframeContents);
			}
		);
		return false;
	});
});

</script>

You also need a php app like this uploader.php to do something with the file:

<?php

$uploaddir = 'uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
$maxfilesize = $_POST[MAX_FILE_SIZE];

if ($maxfilesize > 5000000) {
//Halt!
   echo "Upload error:  File may be to large.<br/>";
   exit();
}else{
    // Let it go
}

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
   print('File is valid, and was successfully uploaded. ');
} else {
   echo "Upload error:  File may be to large.<br/>";
}

chmod($uploadfile, 0744);
?>

Jan 15

Understanding Multidimensional Arrays

An array is a list of values, a data structure made up of a group of elements.

Like appearing out of the fog, arrays became more clear to me only after using them for data storage and transportation in a few programs.  Arrays get a little tricky especially when you start working with the multidimensional kind.

This is the simplest form of arrays, a list of elements.

//a one dimensional array
$fruit = array(apples, bananas, oranges, pears);

Essentially a multidimensional array is an array where the elements of that array are also arrays.  Arrays within arrays.

A two dimensional array would be one array with multiple arrays in it (as it’s elements).  This could be visually represented as a single table of columns and rows.

//a two dimensional array
$fruit = array(
    array(braeburn, granny smith, fuji, gala, golden delicious),
    array(cavendish, ecuadorian dwarf, manzano, lady fingers),
    array(blood, navel, valencia, pineapple, queen),
    array(yellow bartlett, red bartlett, bosc, comice)
);

A three dimensional array would be one array with multiple arrays in it with multiple arrays contained in each one of those.

//a three dimensional array
$foods = array(
    fruits=>array(
        array(braeburn, granny smith, fuji, gala, golden delicious),
        array(cavendish, ecuadorian dwarf, manzano, lady fingers),
        array(blood, navel, valencia, pineapple, queen),
        array(yellow bartlett, red bartlett, bosc, comice)
    ),
    vegetables=>array(
        array(butternut, crookneck, scallop, pattypan),
        array(gherkin, cornichon, garden cucumber, english cucumber),
        array(iceberg, romaine, batavian)
    )
);

There is functionally no limit to the depth of arrays (except your system memory) you can have 4 5 and 6 dimensions (or more) but their use may not be expedient or may unnecessarily complicate things.

Here are a few things that maybe you didn’t know about arrays.

A common task is to take an two dimensional array (such as a mysql query result) and convert it into a tabular display.

$results = mysql_query($sql, $link);</code>

foreach ($results as $row) {
    echo "<tr>";
    foreach ($row as $value) {
        echo "<td>;" . $value ."</td>";
    }
    echo "</tr>";
}

If you want to apply your array into a session variable, such as for a shopping cart, you can use serialize() to put your array into a storable representation of the array, and you can use unserialize() on the other side to put it back into a standard array type variable.

//the output of a serialized array...
a:4:{i:0;a:5:{i:0;s:8:"braeburn";i:1;s:12:"granny smith";i:2;s:4:"fuji";i:3;s:4:"gala";i:4;s:16:"golden delicious";}i:1;a:4:{i:0;s:9:"cavendish";i:1;s:16:"ecuadorian dwarf";i:2;s:7:"manzano";i:3;s:12:"lady fingers";}i:2;a:5:{i:0;s:5:"blood";i:1;s:5:"navel";i:2;s:8:"valencia";i:3;s:9:"pineapple";i:4;s:5:"queen";}i:3;a:4:{i:0;s:15:"yellow bartlett";i:1;s:12:"red bartlett";i:2;s:4:"bosc";i:3;s:6:"comice";}}

Learning about arrays will be worth your time, it will get you thinking about more complex data structures and how to handle them more efficiently. I encourage you to start experimenting with arrays today!

Jan 9

Linux for Windows users

So you want to give Linux a try but you’re not sure if you want to commit?  That would normally mean that you have to either take the plunge and hope you can figure it out or find an old computer to install it on and give it a try.  I have many family and friends who are very familiar with Windows and are just plain afraid to try anything else.   There’s a very exciting program called Wubi that I want to tell you about.  Its been around for just a while now and what it is is a Windows program executable (exe) that installs Ubuntu Linux into a file location on Windows.  Here’s a quote from Wubi:

Wubi is an officially supported Ubuntu installer for Windows users that can bring you to the Linux world with a single click. Wubi allows you to install and uninstall Ubuntu as any other Windows application, in a simple and safe way. Are you curious about Linux and Ubuntu? Trying them out has never been easier!

If you have a high speed internet connection I would recommend trying this free software.  Just run the install program,  Linux will be installed on your system and will be easy to remove if you want later.   I often recommend Open Source software to people around me, and this one is a no brainer.

For a more detailed overview visit http://wubi-installer.org/index.php