The jQuery JavaScript is up and running, but needs a PHP file to handle the Ajax data submitted by the rating script. This will be done with PHP in the receiver you defined in your JavaScript, named “rating.php” in the “public/includes” folder. It’s important to put this PHP file in your public folder, because if you pointed your webserver to “public”, anything outside (subfolders of  your document root) can’t be accessed by JavaScript.

Create the “rating.php”, and add the following lines:

<?php
require_once('bootstrap.php'); // Setup Zend Framework Environment
header("Cache-Control: no-cache");
$rating = new Mylib_Rating_Controller();
$score = $rating->setRatingById($_GET['id'], $_GET['val']); // rate object and get scores
echo Zend_Json::encode($score); // send response array in JSON format
?>

The setRatingById passes the values from your JavaScript to the (soon to be created) controller, and receives the updated values from your (soon to be created) database. When I started out using jQuery in combination with Ajax, I was kind of afraid to find it difficult… but it really is that easy ;-)

Next up: The rating controller

Now for the easy part: creating the page for our jQuery Star Rating plugin. It’s going to be just a bit of HTML, JavaScript with Ajax components, and PHP. If you want to integrate the Star Rating in an existing page, you can just copy the relevant parts into any HTML file.

The JavaScript

Before continuing (or if this doesn’t work for you), you might want to familiarize yourself with the Star Rating plugin at http://zensoftware.org/archives/483.

Add the following lines to the HEAD section of your “index.php”. This assumes that you already have one… if not, use you standard HTML template, and don’t forget to include your bootstrap ;-)

<script type="text/javascript" src="/js/jquery/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="/js/rating/jquery.rating.js"></script>
<link type="text/css" href="/js/rating/jquery.rating.css" rel="stylesheet" media="screen" />

<script type="text/javascript">
$(function(){

 $(".rating")
 .rating({"showCancel": false})
 .bind("change", function(){
   var id = $(this).attr("id");
   var rate = "id=" + id + "&val=" + $(this).val();
   var loading = 'Loading';
   // Or use image instead, looks prettier ;-)
   // var loading = '<img src="/images/loading.gif" />';
   $.ajax({
     type: "GET",
     url: "/includes/rating.php",
     dataType: "json",
     data: rate,
     timeout: 10000,
     beforeSend: function(){
       $("#rating_value_" + id).html(loading);
     },
     success: function(response){
       $("#rating_value_" + id).html(response.average + " points");
     },
     error: function(){
       $("#rating_value").html("Error!");
     }
    }); // end ajax
  }); // end rating / bind

}); // end $()
</script>

I used “loading” as a variable (as opposed to the direct output of “Error!”). You can Google the standard Ajax loading image, and put the HTML image tag in that variable to pretty things up, instead of that boring message.

BTW, I always use a leading slash and the complete path in relation to the root directory (e.g. “/images”) before each image, JS and CSS file. This way, I don’t have to worry about broken links when I split header and content sections into different files, and move them to different directories… which I favorize, because header sections are the same throughout the website, whereas content sections might use different templates.

The PHP / HTML code

You can put this code anywhere within your BODY section of your “index.php”, even in existing pages’ DIVs:

<?php
$id = 1;
$rating = new Mylib_Rating_Controller();
echo $rating->getRatingView($id);
?>

Set the variable “$id” to any unique id you want to rate. On my website surfspot.de, I use it to rate a page, so the id comes from my database, and represents the page id. If you have more than one rating on one page, say for a couple of images, instantiate the class once, and only use echo $rating->getRatingView($id) with a different id for each image.

Next up: The jQuery Ajax receiver

For this article, you should be familiar with at least the basics of Zend Framework, especially naming conventions. If not, check out the ZF site for beginners tutorials and/or Quickstart.

If you don’t want to use ZF at all, but still need the Star Rating with PHP and Ajax, you can skip ahead to the model part.

Bootstraping Zend Framework

The bootstrap file is (simplified) the file where you set up your ZF environment. Bootstrapping ZF in a non-application environment is nothing more that to merely include the bootstrap file manually.

First step after installing ZF and the folder structure in the previous part is to create the “index.php” file in your “public” folder, and a second file in your “public/includes” folder, named “bootstrap.php”. Open “index.php” in your favorite PHP editor, and include your bootstrap:

require_once('includes/bootstrap.php');

Open your bootstrap and add the following lines:

<?php
// Define path to application directory
defined('APPLICATION_PATH')
 || define('APPLICATION_PATH', ($_SERVER['DOCUMENT_ROOT'] . '/../application'));

// Define application environment
defined('APPLICATION_ENV')
 || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'development'));

set_include_path(implode(PATH_SEPARATOR, array(
 realpath(APPLICATION_PATH . '/../library'),
 get_include_path(),
)));

require_once 'Zend/Loader/Autoloader.php';
$autoloader = Zend_Loader_Autoloader::getInstance();
// Register folder library/Mylib/ for custom classes
$autoloader->registerNamespace('Mylib_');

Most lines are copied from the standard ZF bootstrap. We won’t need the APPLICATION_PATH constant for this… I just like to keep it there , in case I switch to application somewhen in the future ;-) Something to keep in mind is the APPLICATION_ENV. You need to change the “development” to “production” when you go live with your scripts – this will be explained in the configuration part.

The important part of the bootstrap is the Zend Autoloader, making sure all ZF components plus your own scripts are found. Nothing magical about it if you know the naming conventions. If not: the autoloader searches for a script by the parts of the class call. If you have a class named “Mylib_Rating_Controller”, Zend fetches it from “library/Mylib/Rating/Controller.php”. The class “Rating_Controller” won’t be found, because it is not defined in your namespace… unless you put $autoloader->registerNamespace('Rating_') in your bootstrap, that is.

Configuration

Next up is the configuration file, where you configure your database (and cache and about a million other things beyond the scope of this tutorial). Create a folder “configs” in your “Mylib” folder, and there a “application.ini” file. Add the following lines of code:

[production]
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
includePaths.library = APPLICATION_PATH "/../library"
database.adapter = "pdo_mysql"
database.isDefaultTableAdapter = true
database.params.host = ""
database.params.username = ""
database.params.password =
database.params.dbname = ""

[staging : production]

[testing : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1

[development : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
database.params.host = "localhost"
database.params.username = "root"
database.params.password =
database.params.dbname = "rating"

Each section inherits from the one before, so if you define your default DB adapter in the production section, your development section will use this default adapter as well. For more information on config files, pls. refer to the ZF manual.

Back to bootstraping

Now it’s time to tell ZF where to get the configuration and database options. Add the following lines to your “bootstrap.php”:

$config = new Zend_Config_Ini($_SERVER['DOCUMENT_ROOT'] . '/../library/Mylib/configs/application.ini', APPLICATION_ENV);
$registry = Zend_Registry::getInstance();
$registry->set('config', $config);

$db = Zend_Db::factory($config->database);
Zend_Db_Table::setDefaultAdapter($db);

Now you are ready to do some coding for the actual task at hand… the rating controller ;-)

Next up: jQuery Star Rating Rating HTML code


My tutorial of utilizing Zend Framework without MVC will be a jQuery rating controller, with ZF used to query the database, spit out the view (the actual stars), and handle rating changes thru Ajax, updating the DB. Though I prefer not to use ZF as an application, I tried to program as close to the MVC structure as possible. If you’re using ZF already, you will see that my way of utilizing it is close to a ZF plugin resource – with some minor changes, you’ll be able to adapt it into the framework in no time at all.

Installing Zend Framework

On your server, add some directories to accomodate ZF, jQuery, and your own PHP files. Assuming that you start from scratch, you need to point your webserver to the “public” directory, instead of “document root”. This way, one can’t access your lib files, e.g. configs, by URL.

> document root
  > library
    > Mylib
    > Zend
  > public
     > images
     > includes
     > js
       > jquery

Download the lastest ZF version at http://framework.zend.com/download/latest, and unpack the files. Get the content of the “library/Zend” form your archive, and copy it into the “library/Zend” folder on your server. Next, get the latest of jQueryUI at http://jqueryui.com/download, and put the content in the “jquery” folder. jQueryUI is just a nice JavaScript framework (that word again…) with widgets and effects… you might need them later ;-)

A short note: though ZF supports the Dojo JavaScript framework, I personally prefer jQuery. Dojo definetly has the cooler widgets, but the support sucks… no forum to speak of, and mailing list support slow if ever. If you run into problems with Dojo, you’re basically on your own… the exact opposite of jQuery, where you 1. get support within hours, and 2. rarely run into problems to begin with ;-) Just my 2 cents…

Anyway, the part missing for our little tutorial is the Star Rating plugin for jQuery. Get it at http://zensoftware.org/archives/483, and put it in your “js” folder, into a “rating” subdirectory.

Next up: Bootstrapping ZF

Typo3: Installation on a shared hoster

Posted: 1st May 2010 by admin in Typo3

Pls. note: these articles were published 2005, and might be outdated

I did some work for a German online magazine for designers and programmers. Those articles might be, or sure are, outdated, but might as well provide some useful information still. If you can either read German, or know Google Translate, go ahead and see for yourself…

Installation auf einem 1&1 Server

Aufgrund der vielen Probleme, die eine Installation bei 1&1 mit sich bringt, habe ich eine kleine Anleitung erstellt, die auch Anfängern in Typo und/oder Linux die Möglichkeit gibt, Typo3 “zum laufen” zu bringen. Minimale Voraussetzung ist das Business Paket ab Version 5.0.

ACHTUNG: der Artikel behandelt die Installation von T3 v.3.6.2, die aktuelle Version 3.8 läuft allerdings stabil auf 1&1. Ein Update von 3.6.2 auf 3.8 ist problemlos möglich. Sollte die EXT indexed_search verwendet werden, müssen alle Tabellen, die die Search benutzt, über PHPMyAdmin geleert werden.

[jd_doc_inst_1und1_v1.2]

Typo3: Magazine articles for Dr. Web Pt. 4

Posted: 1st May 2010 by admin in Typo3

Pls. note: these articles were published 2005, and might be outdated

I did some work for a German online magazine for designers and programmers. Those articles might be, or sure are, outdated, but might as well provide some useful information still. If you can either read German, or know Google Translate, go ahead and see for yourself…

Teil 4 – Typo3: Extensions

Typo3 ist mit 15MB schon eine stattliche Sammlung von Scripts und Funktionen. Trotzdem gibt es Anforderungen, die nicht durch die Standard-Distribution abgedeckt werden. Die Lösung hierfür heissen Extensions, und sorgen dafür, dass Typo3 bis in das kleinste Detail anpassbar ist…

[Typo3_ Extensions]

Typo3: Magazine articles for Dr. Web Pt. 3

Posted: 1st May 2010 by admin in Typo3

Pls. note: these articles were published 2005, and might be outdated

I did some work for a German online magazine for designers and programmers. Those articles might be, or sure are, outdated, but might as well provide some useful information still. If you can either read German, or know Google Translate, go ahead and see for yourself…

Teil 3 – Dynamische Grafiken und DHTML-Menüs

Eine der grossen Stärken des Open Source CMS Typo3 ist die Dynamik. Sei es der Umgang mit dynamisch erzeugten Grafiken für Buttons oder DHTML-Menüs, in Typo3 gehen solche Designelemente fast von alleine…

[Typo3_ Dynamische Grafiken und DHTML-Menüs]

Typo3: Magazine articles for Dr. Web Pt. 2

Posted: 1st May 2010 by admin in Typo3

Pls. note: these articles were published 2005, and might be outdated

I did some work for a German online magazine for designers and programmers. Those articles might be, or sure are, outdated, but might as well provide some useful information still. If you can either read German, or know Google Translate, go ahead and see for yourself…

Teil 2 – Typo3: Designvorlagen und CSS

Moderne grafische Designs umzusetzen erfordert bei den grossen CMS häufig sehr viel Arbeit und Programmier-Know-How. Das Open Source CMS Typo3 bietet hierfür einen einfachen und schnellen Weg: externe Designvorlagen…

[Typo3_ Designvorlagen und CSS]

Typo3: Magazine articles for Dr. Web Pt. 1

Posted: 1st May 2010 by admin in Typo3

Pls. note: these articles were published 2005, and might be outdated

I did some work for a German online magazine for designers and programmers. Those articles might be, or sure are, outdated, but might as well provide some useful information still. If you can either read German, or know Google Translate, go ahead and see for yourself…

Teil 1 – Typo3: Der schnelle Einstieg

Das Open Source CMS Typo3 ist eines der umfangreichsten und komplexesten Systeme am Markt, und so wird mancher Designer oder Webmaster schon verschreckt, bevor er Typo3 testet. Und obwohl Typo3 unzählige Funktionen bietet, ist eine Website schon innerhalb kürzester Zeit aufgebaut. Die Einsatzmöglichkeiten des CMS reichen dabei von der kleinen Vereins-Site bis zur großen Firmenpräsentation…

[Typo3_ Der schnelle Einstieg]

I’ve been looking at a few PHP frameworks to aid the redesign of my website surfspot.de. After toying around with Cake and Symfony for a while, I finally stumbled upon Zend Framework, or ZF for short. When I started out learning ZF, it seemed to me that this was the one framework able to handle whatever tasks I needed, without much of a hassle like CLIs (short for Command Line Interface – just hate them), and with a very good documentation plus forum support.

Now, a couple of months and some 100 liters of coffee later, some parts of the structure of ZF, or even the need for the structure itself, is still a mystery to me. The separation of Model, View and Controller, IMHO, is not too bad in itself, but separating all those components into different directories, as well, only adds to the confusion. In other words, my attention span is just not long enough to figure where to change action, view and so on when those are spread across my whole server ;-)

Anyway, somewhere along the line ZF introduced ” ZF Applications”… including my worst enemy – CLIs ;-) That´s the point where I started to think that it should be possible to use ZF like a “normal” PHP library – the old “include” way – with only those components needed to perform the task. And that’s the beauty of ZF: it is possible. You don’t have to bother with the ZF way of doing things, you can just simply utilize all of their classes to suit your own purpose, in your own way.

In this little series, I will share my experience doing exactly that, hoping you’ll be able to skip some of the pitfalls I came across.