Rotating images using jQuery Ajax

There are many ways to rotate images on a website.  In my case, I needed a way to rotate all images from a particular folder, and I wanted it so that I just have to dump images in the folder in order for the slideshow to pick them up.  ** NOTE: if you want a more advanced setup with database driven slides visit my post about database driven slideshows

For this tutorial I'm going to use jQuery's framework and crossSlide, a plugin for jQuery which will allow smooth transitions between the images.  If you don't have it already, you can get jQuery at www.jquery.com and the crossSlide plugin at www.gruppo4.com/~tobia/cross-slide.shtml .  You'll also have to create a folder with images.  You'll get the best result if all images are identical in size.

A working example can be found at duboistechnologies.com .

Download the code here

Ok, first things first: we'll need a placeholder for the images.  We'll need to specify a fixed height for this placeholder too, otherwise the content below will be jumping up and down every time a new image is loaded:

<div id="imgcontainer" style="margin:0; width:46em; height:20em;">
<img src="img/ajax-loader.gif" style="margin-top:20%" alt="loading…" id="mainImg" />
</div>

I put an image in the div that will show an icon while the images are loaded…

Next step is to create a php page with some code to get all images from the folder.   The getfiles function will get all files and return a string that will be formatted so it can be parsed as separate objects by the javascript eval() function… but that's for later.  We just echo this string so our ajax call will pick it up.  The only thing you'll need to customize is the 'imagefolder'… change this to whatever the name or path is to your folder:

<?php

echo getfiles('imagefolder');

function getfiles($folder=", $extensions='.*')
{

// path:
$folder = trim($folder);
$folder = ($folder == ") ? './' : $folder;

// validate folder
if (!is_dir($folder)){ die('invalid folder given!'); }

// create files array
$files = array();

// open directory
if ($dir = @opendir($folder)){

// get all files:
while($file = readdir($dir)){

if (!preg_match('/^\.+$/', $file) and
preg_match('/\.('.$extensions.')$/', $file)){

// feed the array:
$files[] = $file;
}
}
// close directory
closedir($dir);
}
else {
die('Could not open the folder "'.$folder.'"');
}

if (count($files) == 0){
die('No files where found :-(');
}
// shuffle the array so we have a random sequence of images
shuffle($files);

$return = ";
foreach($files as $file){
// format the string so we can later parse it into objects in javascript
$return .= "{'src':'{$folder}/{$file}'},";
}
$return = "[".substr($return, 0,-1)."]";

// return the string:
return $return;

}

?>

What we need to do now is set up an ajax call that gets the string of images the above function found in my images folder.  We'll also have to include the jquery and crossSlide packages:

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.cross-slide.js"></script>

<script type="text/javascript">
$(document).ready(function(){loadImage();})

function loadImage(){
// getimage.php is the php file that gets my images from the images folder
$.post("getimage.php", function(data){
if(data.length >0) {
// evaluate the string to a group of objects
myObject = eval(data);
// create a slideshow with the image objects and drop them in the placeholder
$('#imgcontainer').crossSlide({sleep:5,fade:2},myObject);
}
});

}
</script>

That's all there is to it.  This is a great alternative to flash and is much less cpu intensive!

Group TD (table data) without using rowspan when left joining in mySQL

When outputting data from a database using left joins you often get redundant data in your output.  Say you have a table with vendor information, and a second table containing the customers for each vendor.  If you want to display a table with the vendor names and their customers, you'll most likely want to use a left join.

The problem is, when you output your data you'll repeat the vendor name for each customer they have.  It makes the table look cluttered and hard to read.  Not to worry though, there is an easy solution!

All you have to do is create 2 classes:

.noblanktd{color:inherit; border-top:1px solid #000; border-top:1px solid #000}
.blanktd{color:white; }

and here's the php code:

function outputmystuff(){
// get your data here eg
$query = "SELECT v.id, v.name as vendorname, c.name as customername FROM vendors as v LEFT JOIN customers as c ON v.id = c.vendor_id";
$result = mysql_query($query);

$oldID = false;
while($row = mysql_fetch_assoc($result)){
$ID = $row['id'];
if($oldID == $ID){
$class = 'blanktd';
} else{
$class = "noblanktd";
}
$returnval .= <<<EOD
<tr>
<td class="{$class}">{$row['vendorname']}</td>
<td class="noblanktd">{$row['customername']}</td>
</tr>
EOD;
$oldID = $ID;

}

return $returnval;

}

and last but not least the html

<table class="repTable">
<tr>
<th>Vendor Name</th>
<th>Customer Name</th>
</tr>
<?=outputmystuff()?>
</table>

Adding additional text fields with Javascript

** UPDATE: This functionality is outdated. Look at a more recent post on how to add more field to a form field:
'Add More' form fields with javascript / jquery **

One of my clients needed the ability for users to refer their family and friends to the website by sending them an email.   The idea was to have 5 fixed fields, and the ability to add more fields on the fly before hitting submit.

Step 1 is obviously adding the static html code (with a tiny bit of php to avoid redundancy):

<form action="mysubmitpage.php" method="post">
<div id='fields'>
<? for($i=1; $i<6; $i++){?>
<div>
name: <input type="text" name="refname<?=$i?>" />

email: <input type="text" name="refemail<?=$i?>"  />

</div>
<? }?>

</div>

<div style="margin-top:5px;">
<input type="submit" value="Send Invitations" name="send" />
</div>

</form>

Step 2 involves adding an 'add more' link, which calls the javascript function that adds the field.  I'm passing the number of the next field into the function, so when the time comes to submit it to the server I can distinguish the fields.  I would have preferred to use IE's outerHTML but that's not supported in my preferred browser firefox, so to keep everything neat I get the existing fields and append the new field to the end of the string.   I also replace the "add more" link so next time it is clicked the number 7, 8, 9 etc is passed.

<script language="javascript">
function addrefField(i){
var newfieldContent = "<div>name: <input type=\"text\" name=\"refname"+i+"\" /> email: <input type=\"text\" name=\"refemail"+i+"\" /> </div> \n";

var oldfieldContent = document.getElementById('fields').innerHTML;

el = document.getElementById('fields');
el.innerHTML = oldfieldContent + newfieldContent;

x = i + 1;
var addmoreContent = document.getElementById('addmorelink');
addmoreContent.innerHTML = '<div><a href="javascript:addrefField('+x+')">add more</a></div><input type="hidden" name="numberfields" value="'+i+'" />';

}

</script>

<div id='addmorelink'>
<a href="javascript:addrefField(6)">add more</a>
<input type="hidden" name="numberfields" value="6" />
</div>

Step 3 : The above code seems to work fine in IE, but in Firefox there is a problem: the value of the existing fields is reset to whatever the DOM originally served up to the user.  So if the user had started to fill out the fields and then clicked the 'add more' link, all fields would have been emptied.  With every problem comes a solution ofcourse.  I googled my problem and stumbled upon this post.  By adding a function (updateDOM()) on the onBlur event for each field, we can update the DOM to reflect the already inserted values.  So here's the entire code for the form:

<script language="javascript">
function addrefField(i){
var newfieldContent = "<div>name: <input type=\"text\" name=\"refname"+i+"\" onBlur=\"updateDOM(this)\" /> email: <input type=\"text\" name=\"refemail"+i+"\" onBlur=\"updateDOM(this)\" /> </div> \n";

var oldfieldContent = document.getElementById('fields').innerHTML;

el = document.getElementById('fields');
el.innerHTML = oldfieldContent + newfieldContent;

x = i + 1;
var addmoreContent = document.getElementById('addmorelink');
addmoreContent.innerHTML = '<div><a href="javascript:addrefField('+x+')">add more</a></div><input type="hidden" name="numberfields" value="'+i+'" />';

}

function updateDOM(inputField) {
// if the inputField ID string has been passed in, get the inputField object
if (typeof inputField == "string") {
inputField = document.getElementById(inputField);
}

if (inputField.type == "select-one") {
for (var i=0; i<inputField.options.length; i++) {
if (i == inputField.selectedIndex) {
inputField.options[inputField.selectedIndex].setAttribute("selected","selected");
}
}
} else if (inputField.type == "text") {
inputField.setAttribute("value",inputField.value);
} else if (inputField.type == "textarea") {
inputField.setAttribute("value",inputField.value);
} else if ((inputField.type == "checkbox") || (inputField.type == "radio")) {
if (inputField.checked) {
inputField.setAttribute("checked","checked");
} else {
inputField.removeAttribute("checked");
}
}
}

</script>

<form action="index.php" method="post">
<div id='fields'>
<? for($i=1; $i<6; $i++){?>
<div>
name: <input type="text" name="refname<?=$i?>" onBlur="updateDOM(this)" /> email:
<input type="text" name="refemail<?=$i?>" onBlur="updateDOM(this)" /> </div>
<? }?>

</div>
<div id='addmorelink'>
<a href="javascript:addrefField(6)">add more</a>
<input type="hidden" name="numberfields" value="6" />
</div>
<div style="margin-top:5px;">   <input type="submit" value="Send Invitations" name="send" /> </div>

</form>

Step 4 : All that's left is processing the fields on the next page:

<?php

$loops = $_POST['numberfields'];
for($i=1;$i<=$loops;$i++){

$namepost = "refname" . $i;
$name = $_POST[$namepost];
$emailpost = "refemail" . $i;
$email = $_POST[$emailpost];
if($name && $email){
echo $name .' ' .$email;
echo '<br />';
}

}

?>