Archive for Blog

AJAX made easy using jQuery

AJAX can seem daunting but it’s never been easier to implement with jQuery! So first, let me give my explanation of what AJAX is and can be used for. Imagine you have a piece of content you’d like to have updated every so often (e.g. an average number from a database), but you don’t want the user to have to reload the page to get the updated number. This is where AJAX comes into play – you can setup an AJAX call to GET the output of a script that queries the database and then use the results to update your page with jQuery. So let’s dive into this example:

index.html

<!DOCTYPE html>
<html>
  <head>  
  <script src="//code.jquery.com/jquery.js"></script>
  <script>
   updateNumber();
   var updateInterval=setInterval(function(){updateNumber()},3000);
			
   function updateNumber()
   {
	$.ajax({
	type: 'GET',
	url: 'ajaxScript.php'
	}).done(function( averageTime ) {
		$("div#num").html(averageTime);
	});
   }
  </script>
  </head>
  <div id="num"></div>
</html>

ajaxScript.php

<?php
  //get the average time from the last 10 minutes
  $stmt = $dbh->prepare("SELECT AVG(time) averageTime FROM `myTable` date >= DATE_SUB(NOW(),INTERVAL 10 MINUTE) LIMIT 1");
  $stmt->execute();
  $row = $stmt->fetch();
  echo $row["averageTime"];
?>

Velocity Cheat Sheet

Decided to make a velocity cheat sheet/quick start guide. Hopefully this is useful for anyone just starting out and also a good reference for experienced velocity developers. If I missed anything feel free to let me know.

## This line is a comment
## The next line is a variable assignment
#set($foo = "hello world")
## The next line uses the variable
<p>$foo</p>
## Velocity is good with dates
<p>Today is $_DateTool.getDate()</p>
## If your using velocity against XML data
## you can get a single node like so:
#set($singleNode = $_XPathTool.selectSingleNode('/path/to/node'))
## or you can select multiple nodes:
#set($multipleNodes = $_XPathTool.selectNodes('/path/to/nodes'))
## and iterate through the nodes like so:
#foreach ($node in $multipleNodes)
    ## You can use if statements like so:
    #if($node.getChild('elementName'))
        ## you can get the child nodes like so:
        $node.getChild('elementName').value
    #end
#end  

Also a useful reference chart provided by XNAT.org (https://wiki.xnat.org/display/XNAT/Velocity+Cheat+Sheet)

Description Usage Example
Variables #set() #set($foo = “hello”)
Comments (single line) ## ## Comment
Comments (multi lines) #* *#  #*
* Comments
* on multiple lines
*#
Arithmetic Operators +   –   *   /   % #set($age = $age + 1)
Comparison
(not just equivalency, can be used to compare objects)
== #if($gender == “female”)
Logic Operators &&   ||    ! #if($state == “Indiana” && $country == “USA”)
Range Operator
(used in loops)
[n..m]
Escape Character
Reference a variable $age <p>Jack is $age years old</p>
Reference a variable
(if value is null, print nothing)
$!age
Assign a value to a variable
(string literal)
#set ( $!foo = “Velocity” )
Refer to a hashtable key
or a get (Address) method
$customer.address
Conditional Statement #if ()
#elseif()
#else
#end
 #if ($foo)
<p>Velocity!</p>
#else
<p>XSLT</p>
#end
Loop #foreach ($criterion in $criteria) ## loop ArrayListCurrent Value: $!criterion#end

Swapping variables in PHP

I’ve created a short and sweet PHP function swap() to exchange/swap the values of two PHP variables. Here it is in action:

<?php

$cat = "cat";
$dog = "dog";

swap($cat,$dog);

echo "$cat goes meow and $dog goes woof"; //dog goes meow and cat goes woof

function swap(&$var1, &$var2) {
    $tmp = $var1;
    $var1 = $var2;
    $var2 = $tmp;
}

?>

If you’re running this function a lot (e.g. millions of iterations) it’s actually faster to just perform the swap without the function. For example:

for($i = 0; $i < 10000000; $i++) {
    $tmp = $var1;
    $var1 = $var2;
    $var2 = $tmp;
}

Thanks @dnaslave for providing efficiency feedback! :]

Matrix like background

<div id="background"></div>

<script>
var int=self.setInterval(function(){updateBackground()},100);
function updateBackground()
  {
    var content = "";
    for(var i=0;i<2048;i++){
      content += Math.round(Math.random()).toString();
    }
    $("#background").text(content);
  }
</script>

<style>
#background {
background: black;
color: #0F0;
width:100%;
word-wrap:break-word;
}
</style>