Category: "JavaScript"

PHP Rating Demo

The basic idea of this rating script is to count the number of votes and the ratings and store them in a text file (a database could also be used).

The first step was to create some images to represent the ratings. The easiest approach was to use ImageMagick to create colorful asterisks.

Next, the javascript was written. There was one minor browser compatibility issue with IE, the margin was not included in the offset. A simple fix was to use PHP to synchronize the left margin in the style tag and to add it in later in the javascript, if it was IE.

Finally, the PHP was written and tested. It is listed below.

rating.php5

$sRatingFile='rating.txt';
if (is_file($sRatingFile))
        $sRating=file_get_contents($sRatingFile);
else
        $sRating="0,0";

$aRating=explode(',',$sRating);

if (isset($_GET['r']))
{
        $r=(int)$_GET['r'];
        if (($r<0)||($r>5)) die('Bad rating');
        else
        {
                $aRating[0]++;
                $aRating[1]+=$r;
                file_put_contents($sRatingFile,implode(',',$aRating));
        }
}
$v=$aRating[0];
if ($aRating[0]!=0)
        $r=(int)($aRating[1]/$aRating[0]);
else
        $r=0;

echo<<<INPUT
<p>
<label>Rating</label>
<input name="iRating" id="iRating" type="image" src="images/$r.rating.png" alt="Rating" onclick="ratingClick(event)" />
$v votes
</p>
<div style="display:none">
<img src="images/$r.rating.png" id="imgRating" />
</div>
INPUT;

In a production environment, some CAPTCHA or other tool should be used to prevent automated submissions.

Optional Parameters - Extending Existing Functions

Both PHP and javascript allow optional parameters and variable arguments.

PHP

javascript

  • The arguments sent to a function in javascript can be accessed as function_name.arguments. To find out how many arguments were passed, you can use function_name.arguments.length. http://www.w3schools.com/jS/js_functions.asp
  • Implementing default arguments with javascript can be done by using the arguments array.

dijit ContentPane Demo - With Refresh and Terminate

The link above demonstrates the use of a dijit ContentPane to request content from the server with a client-side request refresh, and error detection that allows the server to indicate when the requests should be stopped.

The intended use is to allow graceful monitoring of background scripts on a server.

Basic approach:

  • Use the ContentPane to display the content. A quote script is used to illustrate the content change.
  • Use a javascript timer to request a refresh every 5 seconds
  • Have the server-side code count and issue a 303 See Other when processing has completed. http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
  • Have the client-side code catch the 303 and act accordingly. In this case, it changes the displayed text to reflect the status, puts up an alert box, and clears the timer.

Use View Source to view the client-side code, server-side code is listed at the bottom of the page.

This is a nice way to implement a refreshing iframe with dojo.

AJAX Interaction Notes - dojo

Notes on using a dojo/RIA web interface to launch background (server-side) scripts.

  • File uploads can run under FF and IE with dojo.io.iframe.send, and it is a nice interface. There is another post on this blog, with sample code.
  • Synchronizing background server tasks with client launch and monitor requires the client to be able to identify script failure to execute, execute reporting whether the operation was successful or not.
  • Two-phase, asynchronous execution can be made much more secure by storing the second-phase action on the server. Thus, if the first-phase executes correctly, no information is required from the client to continue the operation. All data submitted can be disregarded.
  • Success or Error can be indicated with HTTP headers in cases where no data is required on the response.
  • Client-side redirects can be used to transition to the next phase after a successful run of one phase.
  • User should be alerted that scripts initiated through the web interface cannot be stopped (unless a mechanism is provided).
  • User should be able to return to a previously initiated scripts and view the output.
  • Background script output should be delivered to the initiator through an email. User should be able to suppress email.
  • Background scripts should deliver output in text only.
  • Server must be responsible for state management. Server must ensure background scripts do not collide with each other, or the data, and must provide an interface that allows the client to determine if administration should be readonly or prohibited when specific scripts are executing.
  • Server must be responsible for scheduling resource intensive tasks to prevent service interruptions.
  • An object is an excellent way to allow a single dialog box to submit data to different scripts without writing additional code. The object is then assigned to the AJAX content property.
  • Server must have intelligence to adjust state of client, for example hiding informational messages after termination, enabling buttons to allow continuation, and providing alerts for errors.
  • Initial error reporting can be limited to ‘Error’, a simple indication that something went wrong. After testing, common errors should be delivered with additional explanatory text.
  • Balance distribution of client side code. Although it is nice to split a page into many components that can stand alone, this increases the number of HTTP requests which has performance impacts. Building the javascript into a single file is one solution, bundling related code together is another. Templates should include only the elements that require template processing. Large sections of javascript should be removed. Use caching to improve performance.
  • Break server side code into components such that only the code required to execute is read. This doesn’t always work out perfectly, and there are impacts to opening alot of files as well, but the server impacts are less serious than the client side, because there is no data transfer.
  • Put some timing code into the application so you can see where the time goes. Use YSlow to improve page delivery performance.
  • Use FireBug to monitor traffic between client and server.
  • Use a log file to write out debugging information. Check the error_log frequently. Use echo, var_dump, and exit. Build graceful error reporting into the application from the beginning. This will make debugging much easier. Log all errors. Put a switch in to allow debug displays to be suppressed for production systems.
  • Use a tee (*nix command) to pipe script output to a file and into mail.
  • Document the entire process and describe it to the appropriate people. This will ensure you understand what is happening and that it is what is supposed to be done. Be ready to change.
  • Write a good test plan and use it.
  • Be mindful of security. Validate all inputs. Escape all command line parameters that are user submitted. Check for access privileges for all requests, at all times. Avoid divulging application details or data.
  • Copy script output to a temporary access area, do not grant access further into the server for output display. Identify script output with the script name and session id.
  • Have Apache execute as apache:apache, or nobody:nobody, and allow only those scripts that should be executed through the web to have execute permissions for that user.
  • Be persistent and creative.

Open Source - Cycle Back

Open Source software is often maturing.

Cycling back to the distribution site has many advantages:

  • Upgrading open source components usually delivers many bug fixes and new features. Although upgrading after ever update is probably unnecessary, it is worth considering an upgrade if something isn’t working exactly as expected.
  • Upgrading increases the lifespan of your code, as well as often improving the quality.
  • Documentation often improves, both directly from the author and with contributions from other users. Repeat visits usually increases understanding.
  • As new features are added, they can be integrated into your code.
  • As you learn more, you can contribute to the site.

Cycling back through your application also has many advantages:

  • As your skills improve, your code will, too. Revisiting code allows you to improve it.
  • Look for ways to consolidate and reuse code. The less code you have to maintain, the better. Overly complex or large applications are often more difficult to work with than sleek, elegant systems.
  • Validate XHTML and CSS periodically.
  • Use jsLint, and other tools.
  • Run the pages through different browsers after major changes.
  • Keep an eye on the architecture, understand what goes where and why.
  • Add comments for things that are difficult to understand.
  • Look for opportunities to improve performance.