September 1, 2009 Header

Random Affirmation

Small project that, on click, loads new affirmations. A photo from Leah, some jQuery with AJAX, and voila. I like it.

If anyone has suggestions for a “random thing of the day” type thing, please let me know.

The JavaScript I code to attach the behavior is:

		$.ajax(
			{type: "POST"
			, url: "generate-affirmation.php"
			, beforeSend: function(xhr){
				$('#affirmation').html('<div class="loading"><img src="//cdn.artlung.com/affirmations/ajax-loader.gif" alt="loading..." border="0" height="24" width="24" /></div>');
			return xhr;
			}, success: function(txt){
				$('#affirmation').html(txt).fadeIn('slow');
			}
		});

And the PHP of generate-affirmation.php is:

$raw_affirmations = array();
$raw_affirmations = @file("affirmations.txt");
$raw_commented_affirmations = array();
$html_affirmations = array();

foreach($raw_affirmations as $raw_affirmation) {
	$raw_affirmation = trim($raw_affirmation);
	if((substr($raw_affirmation,0,1) != '#')) {
		if(strip_tags($raw_affirmation) != $raw_affirmation) {
			$html_affirmations[] = $raw_affirmation;
		} else {
			$html_affirmations[] = htmlentities($raw_affirmation);
		}
	} else {
		$raw_commented_affirmations = $raw_affirmation;
	}
}
print $html_affirmations[array_rand($html_affirmations)];

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.