online advertising

Some Good Reasons to Publish Content with JavaScript

I will state here 3 good reasons to publish content with JavaScript;

  1. To hide your forms from spammers’ robots.
  2. To publish content pulled from remote files.
  3. To hide certain content from search engine spiders.

Any HTML content can be generated for delivery with JavaScript. Most JavaScript itself can be delivered that way, should there be reason to do so.

However, don’t generate PHP code or SSI tags into JavaScript. Those have to be available at the server before the page is sent to the browser where JavaScript can run.

1. Hiding Your Forms from Spammers’ Robots.

Spammers won’t spam through your forms if they can’t be found.

The search for vulnerable forms is mostly automated.

Robots follow links until they find a form. The detecting robot then submits the form using preprogrammed methods and with preprogrammed information. If the form has a security hole of the kind the robot is scouting for, the information is recorded for the robot owner’s later perusal.

Manually surfing to find forms and testing them would be uncommon. Spammers seem to be lazy.

Here are the steps to replace the form with JavaScript:

  1. Copy your form’s source code from FORM tag to ending /FORM tag.
  2. Paste the copied code into a JavaScript generator.
  3. Generate the code.
  4. Copy the generated JavaScript.
  5. Replace the current form source code on your web page with the generated JavaScript.

It may be prudent to put a notice on the web page that will be seen only by those whose browsers are JavaScript disabled. Example:

<noscript>
<h3>JavaScript is required to use this form.</h3>
</noscript>

Now you have some protection. It’s not guaranteed to be forever effective, of course.

If you are already being spammed through your form, you’ll need to take a few steps before encoding your form with JavaScript:

  1. Rename your form handling software file on your server. Keep the .cgi (or .pl) file name extension, just change the first part of the file name.
  2. Change your form’s action= URL to reflect the new file name. Every form that uses that form handling software will need this change.

Now you can replace the form with JavaScript by following the steps presented earlier.

The extra step is necessary because your form handling software’s URL is already in the spammer’s database, which means they can bypass the form. Changing the software’s file name introduces an error into their database.

For extra protection, in case robots that can read JavaScript come your way, the JavaScript-ized form can be retrieved from an external file.

2. Publishing Content Pulled from Remote Files.

When certain content is to be repeated on several pages or on several domains, the content is easier to maintain when it exists in only one file.

That content can be generated as JavaScript using a JavaScript generator. Remove the first and last lines from the generated JavaScript (the SCRIPT and cancel /SCRIPT tags) and save the rest as a file on your server.

Convention says the file is to be saved with a .js file name extension. However, .txt or .htm will do the job as well.

Once the file is saved, determine its URL.

Now, all you have to do is put the following JavaScript, with correct URL, into your web pages wherever you want the content to be printed.

<script
   src="http://example.com/file.js"
   type="text/javascript"
   language="JavaScript">
</script>

Replace URL http://example.com/file.js with the URL of your content file and you’re good to go.

3. Hiding Certain Content from Search Engine Spiders.

The following assumes search engine spiders do not read and parse JavaScript. If they do understand JavaScript, now or in the future, other methods can be used to do the hiding.

Certain things are oftentimes best left out of search engine indexes. Examples are advertisements and navigation areas. Their inclusion might contaminate the indexes and even skew your keyword density.

To make ads or other sections of a web page invisible to spiders:

  1. Put the source code section into a JavaScript generator.
  2. Replace the original source code on the web page with the generated JavaScript.

Certain words or phrases, or entire paragraphs, can be hidden from spiders the same way.

An example of why one might want to hide a word, a product name in this case, could be an article reviewing the product. The article has an affiliate link to the product. The page also has AdSense. The name of the product in the article could attract AdSense ads for the product. And that could reduce affiliate income from that page.
There are, of course, other reasons to publish content with JavaScript. Sometimes JavaScript is the only method available. Other times, like the reasons presented here, publishing content with JavaScript is optional.

Whether or not it is optional, a JavaScript generator can help by turning text into JavaScript that will print on a web page.

Very Useful Programing Articles Digest

  • LiMo Foundation: Welcome – Motorola, NEC, NTT DoCoMo, Panasonic Mobile Communications, Samsung Electronics, and Vodafone established the LiMo Foundation to develop the Foundation Platform, a Linux-based, open mobile communication device software platform
  • Erlang, the next Java – Erlang is going to be a very important language. It could be the next Java. Its main problem is that there is no big company behind it
  • Judge Says Unix Copyrights Rightfully Belong to Novell – New York Times – In a decision that may finally settle one of the most bitter legal battles surrounding software widely used in corporate data centers, a federal judge ruled Friday afternoon that Novell, and not SCO, is the rightful owner of the copyrights for Unix OS.
  • NIST endorses Microsoft’s Open XML in upcoming vote | Tech news blog – CNET News.com – The National Institute of Standards and Technology (NIST) is backing Microsoft’s effort to certify Office Open XML as an international standard.
  • How well do you know prototype? – Here, I’ve collected most common use cases that do NOT use all of prototype’s capabilities and their simple solutions. I hope this will be a basic checklist to go through when developing for your next project
  • Learning JavaFX Script, Part 1: An Introduction to JavaFX Script for Java Programmers – The JavaFX Script programming language (hereinafter referred to as JavaFX) is a declarative, statically typed scripting language from Sun. Because JavaFX Script is statically typed, it also has the same code structuring, reuse, and encapsulation features
  • Real Web 2.0: Quick and dirty Web applications with bookmarklets – Bookmarklets are an important part of the Web 2.0 landscape, and they exemplify the qualities of Web 2.0 technology I tend to focus on in this column: transparency and openness.
  • WebLogic Server Virtual Edition Launcher Appliance – WLS-VE is a combination of a Java application server (WebLogic Server) with a Java Virtual Machine that works with hypervisor software and provides only the set of operating system features that WebLogic Server needs to offer its full range of services.
  • Arvind Jain’s Blog: WebLogic Server Virtual Edition (WLS-VE) goes GA – With a single command, WLS instances can quickly be deployed onto VMware ESX-enabled resource pools, fully integrated and tuned to run within their own dedicated virtual machines… all without any 3rd party operating systems.
  • yav – Javascript form validation tool – Yav is a SIMPLE, POWERFUL and CUSTOMIZABLE javascript-based form validation tool.
  • New elements in HTML 5 – HTML 5 introduces new elements to HTML for the first time since the last millennium. New structural elements include aside, figure, and section. New inline elements include time, meter, and progress. New embedding elements include video and audio.
  • Download Query Express – Query Express is a simple Query Analyzer look-alike, but being small and free it can be run where the SQL Server client tools are not installed or licensed. This makes it especially useful as a query tool for MSDE and SQL Express. It also connects to Orac

Another Digest On AJAX Tutorials

  • InfoQ: System Integration Testing Using Spring – When it comes to system integration testing Spring adds real value. In this session, Rod Johnson discusses: integration testing and the support that Spring provides for it, issues around testing the persistence layer, testing web applications.
  • InfoQ: BEA and Oracle incorporate Sun’s Project Tango – In a recent article, Sun’s director for SOA products, Kevin Schmidt mentioned the fact that both Oracle and BEA have incorporated Sun’s Web Services stack, Project Tango. Tango is MS .NET 3.0 interop
  • InfoQ: Using Java to Crack Office 2007 – With Office 2007, no third-party libraries are necessary-a Java application can now read and write any Office 2007 document, because Office 2007 documents are now nothing more than ZIP files of XML documents known as the OpenXML
  • Welcome to jXLS – jXLS is small and easy-to-use Java library for generating Excel files using XLS templates. Also jXLS can be used to read XLS files and populate Java beans with spreadsheet data according to XML configuration file
  • How To Read / Write Excel Spreadsheet From Java – Both JExcelAPI and Jakarta POI (HSSF) are open source software to read & write data from / to Excel spreadsheet even on non-Microsoft platforms. In my tests HSSF came out to be the clear leader and recommended solution because of robustness and features.
  • Eloquent JavaScript – Eloquent JavaScript is a hyper-book providing a comprehensive introduction to the JavaScript programming language. Apart from a bookful of text, it contains plenty of example programs, and an environment to try them out and play with them.
  • http://www.ietf.org/internet-drafts/draft-ietf-atompub-protocol-17.txt – The Atom Publishing Protocol (APP) is an application-level protocol for publishing and editing Web resources. The protocol is based on HTTP transfer of Atom-formatted representations. The Atom format is documented in the Atom Syndication Format.
  • F1 News – Grandprix.com – One of the big problems with the ongoing Stepneygate Affair is that there is a huge amount of hearsay, but not a great deal of fact
  • YUI 2.3.0: Six New Components and a Prettier Face » Yahoo! User Interface Blog – We’re pleased to announce the release of YUI version 2.3.0. This release features six new additions to the library as well as a new skinning architecture and a new visual treatment for most of our UI controls – plus 250 enhancements and bug fixes
  • Greg the Architect : Episodes – Find out what happens when Greg tries to swallow three different SOA pitches in one day. Will he save the day, or will Greg have to chuck the project?
  • Dr. Dobb’s | Java Message Service | July 2, 2007 – SOAP-based web-service development continues to grow, and uses XML and HTTP to remove the implementation details from remote procedure calls. But while SOAP has broken new ground in distributed computing, message-oriented middleware such as the Java Messa
  • Plans for the Rich Web Application Backplane – Both mashups and Ajax are now firmly entrenched in the Web landscape. Put them together and you have the makings for Rich Web applications. This article explains the Rich Web Application Backplane, currently a W3C Note, which is designed to bring standard
  • 10 things I learned about using Hibernate/JPA successfully by SpencerUresk – I decided to share a few things I learned about using Hibernate/JPA in a large project with a complicated database setup
  • OpenJPA no longer requires bytecode processing – Historically, OpenJPA required that you either run a post-compilation tool or run your application with a javaagent. The latest build of OpenJPA removes this restriction by providing various levels of support for unenhanced classes.

AJAX Tutorials Collection

Some Ajax Examples and Demos (XMLHttpRequest)

Ajax examples (XMLHttpRequest examples), code snippets and proof of concepts – the links below should help get you started on building your own functions with XMLHttpRequest and Ajax.

Loading XML into a page with xmlHttpRequest

A cool little blog post and demo that Retrieves an xml atom feed and xsl stylesheet with XMLHttpRequest().

XMLHttpRequest, REST and the Rich User Experience : Paul James

Paul James gives the basics of getting started with XMLHttpRequest and using REST for attaching the client-side to the server.

He builds an example where, upon entering a postal code and pushing a button, a form queries the server for the rest of the address information and fills in the appropriate fields when the data is returned.

Using the XML HTTP Request object

Jim Ley provides his overview of the XML HTTP request object, getting into some browser details and detection before providing some examples and getting into using XMLHTTP with google’s SOAP API.

Very Dynamic Web Interfaces – XMLHttpRequest

Drew McLellan provides an excellent overview of the basics of using XMLHttpRequest offering up a simple, well documented example used for checking if a username is available (similar to g-mail).

Client Side Validation Using the XMLHTTPRequest Object

An example of using XMLHTTP to perform real time data validation, in this example for validating data entered into a user registration form. The example focusses on Microsoft and ASP.

XMLHttpRequest Demo

Three examples of XMLHttpRequest in use: autocomplete, live search, and live action.

To Do with Ta-da List: Simple sharable to-do lists.

A free web based to-do list application provided by 37Signals, makers of Basecamp. Sign-up and try it out; XMLHttpRequest in action.

XHConn – A Simple XMLHTTP Interface

From the site: This library is meant to simplify and unify the code necessary to successfully send and receive simple data via XMLHTTP.

XMLHttpRequest API madness

Two scripts that use XMLHttpRequest: 1 – a javaScript interface to the languid.cantbedone.org API and 2 – a javaScript interface to the del.icio.us API.

Dynamic HTML and XML: The XMLHttpRequest Object

Apples page on the the XMLHttpRequest object, covering object creation, methods and properties in addition to security issues. They build an example for reading XML data, by retrieving iTunes RSS feeds that you select from a dropdown menu.

LiveSearch – Bitflux Blog Wiki

The wiki page for the livesearch function. From the page: On the client side, we use XMLHttpRequest for sending the request to the server. There we have a little PHP script, which returns a small HTML file (http://blog.bitflux.ch/livesearch.php?s=PHP ) . This is then inserted into the page with some DOM manipulation.

XMLHttpRequest and innerHTML

XMLHttpRequest is one of modern DHTML’s best kept secrets. – Haha, not anymore! Simon Willison offers up a little code that takes an HTML fragment, fetched via xmlhttp.open, and inserts it into an element with a specified id. Some good links and comments follow the article.

Google Suggest feature with ASP.NET 2.0

This article provides an ASP.NET 2.0 angle of Google Suggest along with a short little look at the history of javascript, frames, remote scripting and XmlHttp + XMLHttpRequest.

A nice overview of the history and a good breakdown how the Suggest feature works.

SAJAX – Simple Ajax / xmlHTTPRequest Toolkit for PHP

From the site: Sajax makes it easy to call PHP functions from your webpages via JavaScript without performing a browser refresh. Worth checking out and having a play with.

Amazon Zuggest

From the site: This is my take on Google Suggest only with Amazon so I’ve called it “Amazon Zuggest”. Head on over and give this a try.

Francis writes “The Javascript runs in the browser and fires every so often, looks for something to search on, it shoots a request using XMLHttp to my webserver, which in turn creates a SOAP message that gets sent to Amazon. They send back the content and it’s formatted on the server, then streamed to the browser. All in the blink of an eye.

This is a cool little app. When you are done searching, have a hover over the “History” list in the left hand column… The site comes up a little messy in Firefox…

Instant Edit

Manolo Guerrero sets up a little app that allows you to click on a form field and edit the text, which is automatically saved to the server via xmlHttpRequest. Worth a look, though the commented Javascript is in Spanish.

AJaX for weblogs

A neat little script to play with (not sure what it has to do with weblogs especially tho). From the site: It uses Javascript to get data from a remote source and then loads that into a specified target. Whatever content you like to wherever you like on the page.

AJAX Login System Demo

A proof of concept, Ajax based login script that, in this case, uses a php/mysql backend. The author provides all of the scripts involved and lists some advantages and dis-advantages of his method.

Usable XMLHttpRequest in Practice

Thomas Baekdal gets back into accessibility and Ajax. From the site: Let’s look at what we can do to turn an otherwise user-hostile XMLHttpRequest application – into a usable one…. An excellent write-up.

XHTML live Chat via XMLHttpRequest

An excellent proof of concept and something I was waiting for someone to code up ;-). This XHTML live Chat uses XMLHttpRequest to post chat messages and to periodically check the server for new messages and update your chat window.

This is simply a proof of concept, and would work really well in a blog commenting setting or for forums when those fast threads start happening.

Ripped Tickets – Live Search

Here’s an excellent application of the livesearch idea that has been seen around the web. Type in your search (a band name) and the results show up in a nice table below the search box.

Running XMLHttpRequest with Java on Google’s API

Similar to other livesearch functions out there, only this one plugs into Google’s API and has a Java backend, returning a list of results and descriptions for your query.

SproutLiner

From the site: Sproutliner is a free web service that helps you manage your projects and ideas. This tool looks to be very promising, and to be honest you have to try it out to ‘get it’. It is a sort of Ta-da list on steroids, so to speak, in that it is very simple yet a user can add to it and tailor it to their needs.

Very cool…

The Fonz uses XmlHttpRequest and AJAX to spy on you.

While makaing some excellent points in the article, the little adventure game “The Search For Fonzie’s Treasure” built using Ajax technologies is pretty cool. The author discusses user profiling as an “evil use” of Ajax. I’m not so sure that I would say that it is evil…

Backbase – Rich Internet Applications

A very impressive piece of Ajax work, with some context provided here. Have a click thru the site and try out that back-button. Also be sure to head in and check out the demo section.

Big List Of More AJAX Tutorials

With the popularity of AJAX growing every day I’ve had the opportunity to collect and try out many more tutorials in the last several months. These examples and how-to’s represent the best tutorials that I’ve personally used or otherwise had the opportunity to work with out of the overall group. This post is intended for individuals who learn best by example. Most of the listed tutorials come complete with instructions and source code. I’ve also categorized all of the tutorials for easy browsing.

AJAX Activity Indicator Tutorial
CakeTimer – An Ajax File Uploads Progress Bar
This is a demonstration of an AJAX powered progressbar to monitor file uploads with (Cake)PHP.

HowTo add Ajax in-progress indicators
Ok, so my little del.icio.us app (click link to read about how I added Ajax functionality to a simple Rails app) is pretty cool, but it was missing one big thing. When the user clicks the “Get Results” link she has no idea that the page is communicating with the server.

AJAX Bookmarklets Tutorial
Creating Huge Bookmarklets
A bookmarklet is a special piece of JavaScript code that can be dragged into a user’s link toolbar, and which later can be clicked on to implement cross-site behavior. People have done all sorts of cool stuff with it.

AJAX Chat Tutorials
AJAX Chat Sources Code for Download
After a slow start (following the announcement of the XHTML (ajax) Chat) things got finally busy. I had so many requests that I have decided to offer the complete sources for download.

Lace – Ajax Chat
Lace is a free, lightweight Ajaxian communications engine suitable for a shoutbox, chat room or similar. Version 0.1.3 brings with it several bug fixes, a tiny bit of code reorganization and most importantly, an oft-requested User List.

Most Simple Ajax Chat Ever
Very easy to use AJAX chat demo.

AJAX Client-Server Communication Tutorials
Implementing simple AJAX interaction in your Web Application using XMLHttpRequest object
Everybody till now must have atleast heard about AJAX (Asynchronous JavaScript And XML). This example will give you an idea about how you can implement simple AJAX interaction in your web application.

Make asynchronous requests with JavaScript and Ajax
In this article, you’ll begin with the most fundamental and basic of all Ajax-related objects and programming approaches: The XMLHttpRequest object. This object is really the only common thread across all Ajax applications and — as you might expect — you will want to understand it thoroughly to take your programming to the limits of what’s possible.

Advanced requests and responses in Ajax
n this article, I move beyond the basics in the last article and concentrate on more detail about three key parts of this request object, the HTTP ready state, the HTTP status code and the types of requests that you can make

AJAX
In this tutorial, you’ll be introduced to Ajax, a technology that allows you to send these requests through small JavaScript calls, meaning the user doesn’t have to wait for the page to refresh.

All Request, All The Time
Let’s build a simple application that accepts input from the user, passes it to some PHP on the server that checks it against a database, and returns the result to the browser. It comes in three parts.

AJAX Drag and Drop Tutorial
Drag and Drop Tutorial (with a cool video)
Adding items to a shopping cart in common e-commerce applications isn’t very close to the actual “add to cart” metaphor, since it requires clicking an “add to cart” button, watch a new page (the shopping cart), and then go back to the shop or checkout with buttons. Ajax allows to get closer to the cart metaphor, by enabling drag-and-drop interactions and giving immediate visual feedback, without leaving the shop.

AJAX Dynamically Content Loading Tutorials
Dynamically loaded articles
This is a basic example showing you how to use AJAX. In this script, you have a list of article titles at the right side. When you click on one of them, AJAX will be used to request the content of the article from an external file and show it in the main DIV.

Ajax – Dynamic Content
This small generic script makes it easy for you to load content of external files into HTML elements on your page.

AJAX Forms and Autocomplete Tutorials
Scriptaculous Lists with PHP
The drag-and-drop effects, most notably the sortables, caught my eye because the look great, they are so easy to implement, and they’re just so much nicer than the standard listbox with up/down arrows that we see in most of today’s applications and administration tools.

Alter data with Ajax forms
Displaying rich formatted questions and lists, even paginated, is not enough to make an application live. And the heart of the askeet concept is to allow any registered user to ask a new question, and any user to answer an existing one. Isn’t it time we get to it?

Dynamic Client Lookup
This script uses AJAX to autofill a form. Open the demo and type in 1001 in the “client ID” text field. AJAX will when you have done this call a script on the server and auto fill the rest of the form with client data.

Chained Select Boxes
This script uses Ajax to popuplate a select box with cities based on which country you choose.

Ajax Dynamic List
This script shows you a list of options based on what you type into a text input. Example: Type in “A” and Ajax will get you a list of all contries starting with “A”.

AJAX Framework and Toolkit Tutorials
My-BIC – Tutorials and How To’s
A collection of easy to follow tutorials using the My-Bic Framework including a, hello world – getting your ajax setup, posting comments via AJAX and changing views from a drop down. There are beginner and intermediate tutorials here.

New Echo2 Tutorial Series
Part 1 of a multipart Echo2 tutorial series, entitled “Ajax with Echo2 and Eclipse” is now available from our web site. The related archive with the Echo2 distribution plus the EchopointNG library is available here.

AJAX Design Patterns – Using The Dojo Toolkit
Is this tutorial any different from the others? Well yes and no, it is different in being a tutorial on how to design and build a complete site and not just some fancy little details like how to turn caching in AJAX off or how to create a fancy widget.

Using Dojo and JSON to Build Ajax Applications
In this article, I will show how to build Ajax-enabled applications using Dojo and JSON–two very different but complementary technologies that can significantly enhance the interface and usability of web applications.

AJAX General Tutorials
Building a Spy
Step by step instructions on how to build a Digg like spy page.

Building a Shelf in WordPress
Nice tutorial on how to build a sliding shelf in Wordpress.

AJAX from Scratch: Implementing Mutual Exclusion in JavaScript
This AJAX from Scratch series of articles describes fundamental techniques needed to develop AJAX Rich Internet Applications in JavaScript from scratch.

Saving Session Across Page Loads Without Cookies, On The Client Side
This is a mini-tutorial on saving state across page loads on the client side, without using cookies so as to save large amounts of data beyond cookies size limits.

A Tale of Two IFrames or, How To Control Your Browsers History
This is a mini-tutorial on the black art of iframes and browser history, known to AJAX experts but rarely presented clearly.

AjaxWorld Special: What Is AJAX?
Learn more about AJAX and ColdFusion

Simple Ajax Functions – Snippets
I’ve created a list of very common JavaScript functions for Ajax. They have been created in quick reference fashion and do not contain any fancy stuff. Instead of creating one function which can handle various tasks depending on passed values, they are split into seperate basic task functions. The reason for this is simplicity.

AJAX Using ASP.NET 1.1
You’ve heard of it. It is the latest buzz term for web programmers these days. AJAX is an acronym that stands for Asynchronous JavaScript and XML. AJAX gains its popularity by allowing data on a page to be dynamically updated without having to make the browser reload the page. I will describe more about how AJAX works, and then go into some sample code to try out.

Speed up Your AJAX Based Webapps
It sets the expiry of the JavaScript to years and not days. Once the JavaScript file is downloaded it is never downloaded again, ofcourse unless you force it by removing the file in the cache. If you visit the site often the JavaScript will not be removed from the cache.

Kick-start your Java apps, Part 2
This tutorial guides you through the development of a small human-resources application, first using conventional JavaServer Pages (JSP) based technology, and then migrating it to a highly interactive solution using Ajax.

Howto integrate Google Calendar in your website using AJAX
One of the features I find it interesting in Google calendar is the possibility to create shared calendars, but also the availability of your calendar as XML or ICAL whatever it’s a private or public one. As soon as we have XML of our calendar available I was wondering why not integrating Google calendar directly in website.

Create Your Own Ajax Effects
Why let script.aculo.us have all the fun? Start building your own Ajax-driven visual effects today. The basic and prebuilt effects in script.aculo.us are nice, but if you really want to build something great why not investigate doing your own, homegrown, do-it-yourself effects. We’re going to show you how to take basic effects and build on them to create your own.

AJAX Getting Started Tutorials
An Introduction to AJAX
A very nice introduction to AJAX.

Nitty Gritty Ajax
In the course of this tutorial, we’re going to look at what Ajax can do. Then we’ll use a JavaScript class to simplify your first steps toward the ultimate in speedy user interactivity.

A simple AJAX example
Based on Rasmus’s 30 second AJAX tutorial, I’ve cobbled together a very rudimentary example of one approach to AJAX programming. A “Hello, World” AJAX program, if you will. You can view the demo here on my site, and download the source code (document attachment at the bottom of this article).

A List Apart: Articles: Getting Started with Ajax
The start of 2005 saw the rise of a relatively new technology, dubbed “Ajax” by Jesse James Garrett of Adaptive Path. Ajax stands for Asynchronous JavaScript and XML. In a nutshell, it is the use of the nonstandard XMLHttpRequest() object to communicate with server-side scripts.

Ajax Toybox
Justin has put together a nice group of AJAX tutorials including, Hello, World, Dynamic City, State Lookup, Ajax to Clean Your Clock, Ajax Calculator and an RSS News Ticker.

Introduction to Ajax
When it comes to Ajax, the reality is that it involves a lot of technologies — to get beyond the basics, you need to drill down into several different technologies (which is why I’ll spend the first several articles in this series breaking apart each one of them).

Ajax Toolbox / XMLHttpRequest AjaxRequest Library Examples
A great group of AJAX examples.

Rasmus’ 30 second AJAX Tutorial
I find a lot of this AJAX stuff a bit of a hype. Lots of people have been using similar things long before it became “AJAX”. And it really isn’t as complicated as a lot of people make it out to be. Here is a simple example from one of my apps.

An Ajax “Hello World” project to Get You Going
Sometimes we all want something very simple to build a thorough understanding of the mechanics of a new technique before we dive into the deeper water beyond. Now, if you are into ASP.NET and not PHP you might like to take a look at my version of this ultra-simple introduction to Ajax with sincere thanks to the original author.

Ajax Beginners Tutorial
In this tutorial we’ll discuss the basic principles of remote scripting using Ajax, a combination of javascript and XML to allow web pages to be updated with new information from the server, without the user having to wait for a page refresh.

AJAX Image and Gallery Tutorials
Image crop – DHTML user interface
This script gives you an Image crop/resize DHTML user interface. Drag a rectangle around the area you want to crop. Click the “Crop” button and let Ajax send crop data to the server and the cropped image back to you. PHP uses ImageMagick on the server to crop and convert the image.

Prototype Javascript Lightboxes
This class is based on Prototype 1.5. The code is inspired of the powerful script.aculo.us library. You can even use all script.aculo.us effects to show and hide windows if you include effects.js file.

AJAX Sortable List Tutorial
How to Make Sortable Lists
Many web applications need to offer an interface to order items – think about categories in a weblog, articles in a CMS, wishes in an e-commerce website… The old fashion way of doing it is to offer arrows to move one item up or down in the list. The AJAX way of doing it is to allow direct drag-and-drop ordering with server support.

AJAX RSS Tutorials
Simple Ajax RSS ticker script
This very small and simple script reads RSS data from an external source and shows them inside a predefined box DIV or other tag) on your page. What you have to do is to specify the url to the RSS feed, how many items you want to show, and for how many seconds you want the script to display each item.

Dragable RSS boxes
This is is a script that uses Ajax to read data from external RSS sources and display them inside dragable boxes. You can also create new boxes dynamically directly from the page. This is the first version of this script. New functionality will be added to this script during the following weeks and months.

Slide In RSS items
This scripts reads RSS feeds from an external source and displays them on your page. Each items appears after a predefined number of seconds by sliding in from the right side.

RSS Ticker with AJAX
Well, with this powerful RSS ticker script, you can now easily display any RSS content on your site in a ticker fashion! This script uses a simple PHP based RSS parser called LastRSS for retrieving a RSS feed, then Ajax and DHTML to display the feed dynamically and with flare. As a pre-requisite then, your site itself must support PHP, though the page using this ticker can be any regular HTML file.

AJAX Shopping Cart Tutorials
Fly to basket (Shopping cart)
This is a DHTML shopping cart module. The products will fly to the shopping basket when you click on the “Add to basket” button. Ajax is used to dynamically update the content of the basket.

Flexstore on Rails Tutorial
Flexstore is a traditional Shopping Cart application that you can write in Ruby on Rails. Very comprehensive and cool.

AJAX Sorting Tutorial
Sorttable: Make all your tables sortable
While the web design community gradually moves away from using tables to lay out the structure of a page, tables really do have a vital use, their original use; they’re for laying out tabular data.

AJAX Trees Tutorials
Update a tree with AJAX
his scripts adds an AJAX extension to my static folder tree. Open the demo and press down your mouse button on one of the nodes in thee tree. This will make a text box appear which makes it possible for you to rename nodes. AJAX is used to send this value to the server without reloading the page.

Static list based folder tree
This is a list based folder tree. What you have to do is to create a UL LI list. The script will then create the tree based on this list. The script uses cookies to remember state of nodes. It also includes functions for expanding/collapsing all nodes.

AJAX Username Availability Tutorial
AJAX username availability checking
The goal of this AJAX example is to allow a user who is registering for your site to see if the username they want to use is taken already or not, without having to submit a form and reload the page.

AJAX Voting Tutorial
Digg-like AJAX Vote On
This tutorial will show you how to add AJAX-enhanced interactions to askeet. The objective is to allow a registered user to declare its interest about a question.

Ajax Poller
A poller script that uses Ajax to send vote to the server and receives vote results from the server. The results are displayed in some animated graphs.

Web Development Resource Articles

Member Managment System Using PHP, AJAX – Part 3

In parts one and two of this tutorial we covered the user side of things, now we have to handle our administration area. This is going to be pretty simple, but the cool thing is that it will integrate totally with all our existing code.

In order to protect the PM page from guests, we set our MIN_AUTH_LEVEL constant to 1, so all we need to do in order to only let administrators in is to make that value 2. Sweet.

All the admin panel will do is let you edit users data (not password, you sneaky little. . .) and gives a simple splash page with some basic stats.

File: admin.php

 

<?php
session_start();
//Only administrators can get in here
define(‘MIN_AUTH_LEVEL’, ‘2′);
include(‘./config.php’);
//Only one option, eh.
$menubar = ‘<table><tr><td><a href=”?do=users”>Manage Users</a></td></tr></table>’;
$footer = “<p><a href=’”. SITE_URL .“‘>Home</a> – <a href=’”. SITE_URL .“login.php?do=logout’>Logout</a></p>”;
if($_GET['do'] == )
{
//Basic information, pretty much useless in our case, but may not be for others
$title = ‘Admin Home’;
$con = “<h2>Admin Home</h2>
Quick Stats:
<ul>
<li>Members: “
. count_tbl(‘users’) .“</li>
<li>PM’s: “
. count_tbl(‘messages’) .“</li>
</ul>”
;
}

The above is just setting the auth level, than doing our simple, and rather pointless, splash page. Next up is the cool part, the user editing. No, there’s no reloading the page, you just click save or delete and it’s done, all with some pretty effects. We’re going to use our get_all_users() function to return a neat array of every user, then all we do is foreach() through each one.

File: admin.php (continued)

 

else if($_GET['do'] == ‘users’)
{
//Get an array of every user we have
$users = list_all_users();
$title = “Manage Users”;
$con = “<h2>Manage Users</h2>
<p>Click the save icon to update the user’s details, and the x to delete the user (not undoable!)</p>
<form>
<table border=’1′>
<tr><th>Username</th><th>Name</th><th>E-Mail</th><th>Auth Level</th><th>Options</th></tr>”
;
//A mess of code, I know. It lists the details for every user, except password, and assigns each TD a unique ID so that the JS can get the value when saving. The icons let you save your work or delete the user.
foreach($users as $v)
{
$con .= “<tr id=’user_{$v['id']}’><td><input type=’text’ id=’username_{$v['id']}’ value=’{$v['username']}’ /></td><td><input type=’text’ id=’name_{$v['id']}’ value=’{$v['name']}’ /></td><td><input type=’text’ id=’email_{$v['id']}’ value=’{$v['email']}’ /></td><td><input type=’text’ id=’auth_{$v['id']}’ value=’{$v['admin']}’ /></td><td align=’center’><a href=’#’ onclick=\”edit_user(’{$v['id']}’);\”><img src=’./images/save.png’ alt=’save’ style=’border:none;’ /></a> – <a href=’#’ onclick=\”delete_user(’{$v['id']}’, ‘{$v['username']}’);\”><img src=’./images/delete.png’ style=’border:none;’ alt=’delete’ /></a></td></tr>”;
}
$con .= “</table></form>”;
}
?>

There’s not much going on there other than the mass of ugly looking code. The $v variable is the array of the current user’s details, which is assigned by the foreach loop. Now comes the hard part, well kind of, the JavaScript. After this we’ll be done! :)

File: admin.php (continued)

 

<html>
<head>
<title><?php echo $title; ?></title>
<script src=‘../../scriptaculous/prototype.js’></script>
<script src=‘../../scriptaculous/scriptaculous.js’></script>
<script type=‘text/javascript’>
//Get every new value, taken from our unique IDs assigned earlier.
function edit_user(uid)
{
var opt = {
method:‘post’,
postBody:‘m=edituser&id=’ + uid + ‘&username=’ + $F(‘username_’ + uid) + ‘&email=’ + $F(‘email_’ + uid) + ‘&name=’ + $F(‘name_’ + uid) + ‘&auth=’ + $F(‘auth_’ + uid) +‘&password=<?php echo $user['password']; ?>’,
onSuccess: function(t) { handle_edit(t, uid); }
}
new Ajax.Request(‘./ajax.php’, opt);
}

function handle_edit(t, uid)
{
if(t.responseText == “1″)
{
//Give a pretty notice to say that it was saved
new Effect.Highlight(‘user_’ + uid);
}
else
{
alert(“The user’s data was not updated, please try again.”);
}
}

function delete_user(uid, username)
{
//Confirm the delete
if(confirm(“Are you sure you want to delete “ + username + “?”))
{
var opt = {
method:‘post’,
postBody:‘m=deluser&id=’ + uid + ‘&password=<?php echo $user['password']; ?>’,
onSuccess: function(t) { handle_delete(t, uid); }
}
new Ajax.Request(‘./ajax.php’, opt);
}
}

function handle_delete(t, uid)
{
if(t.responseText == “1″)
{
//Remove the user from the table very nicely :)
new Effect.Fade(‘user_’ + uid);
}
else
{
//Agh!
alert(“The user was not deleted, please try again.”);
}
}
</script>
</head>
<body>
<?php echo $menubar, $con, $footer; ?>
</body>
</html>

You should be familar with making AJAX requests now, you may notice our use of Effect.FadeOut and Effect.Highlight, these are just built in script.aculo.us effects that make UI very pretty. This is it for the tutorial, it’s definitly been a long one. I’ll try to get a working version up soon with public admin access, but I’ll have to modify some code so you guys don’t go to overboard.

A full set of files used in this tutorial can be downloaded here

Member Managment System Using PHP, AJAX, – Part 2

In part 1 of this tutorial, we laid the ground work for the entire system. That included the core functions, and the AJAX handler, which receives + handles the AJAX requests (deja vu?). We also made the login page, which also handles registration and logging out.

In part 2, we’re going to create the user’s main page, the private messaging system, and the settings manager, where uses can change there name, E-mail, and password.

When a user sucessfully logs in, they are redirected to index.php, which will simply greet them and give them a few links. If a guest vists that page, a message telling them to register or login will appear. The index page also manages your settings.

File: index.php

 

<?php
session_start();
//Load up userdata, database connection, functions
include(‘./config.php’);
//Display a guest message
if(!check_login($username, $password))
{
$title = “Guest Page”;
$con = “<h2>Welcome Guest</h2>
<p>Hi there. I see that you’re a guest to this site, in order to get the best experience out of “
. SITE_NAME .“, you must be registered. Registering is totally free and requires only a few minutes of your time, we promise! If you’re interested, you can register <a href=’login.php?do=reg’>here</a>.</p><p>If you’re not a guest, and simply haven’t logged in, you may log in <a href=’login.php’>here</a>.”;
}
else
{
//Footer links
$footer = “<p><a href=’index.php’>Home</a> – <a href=’login.php?do=logout’>Logout</a></p>”;
//Welcome message with options
if($_GET['do'] == || !$_GET['do'])
{
$title = $user['name'] .“’s Control Panel”;
$con = “Welcome {$user['name']} to your very own control panel. Here you can <a href=’pm.php’>view</a> and <a href=’pm.php?do=send’>send</a> messages to other members, and control your <a href=’?do=settings’>settings</a>.<br /><br />”;
//This counts the number of unread PM’s the user has
$unread = count_unread($user['username']);
//Give a message if it’s greater than 0
if($unread > 0)
{
$con .= “<span style=’color:red; font-weight:bold;’>You have $unread unread private message(s)</span>”;
}
}

Don’t save that file yet, we’re not done! Our last part will display the settings page. script.aculo.us makes in place editing easy, but it still could be improved. However, it’s definitly functional, and is very easy to implement. In order to make a field editable, we just put this JavaScript snippet in:

 

new Ajax.InPlaceEditor(element_id, url);

That snippet must be after the element is declared, but that’s no trouble. The password changer also uses AJAX, but no in place editing.

File: index.php

 

else if($_GET['do'] == ’settings’)
{
$title = ‘Manage Your Settings’;
$con = “<h2>Personal Settings</h2>
Name: <span id=’name’>{$user['name']}</span><br />
E-Mail: <span id=’email’>{$user['email']}</span>
<script type=’text/javascript’>
new Ajax.InPlaceEditor(’name’, ‘ajax.php?m=optsave&type=name&id={$user['id']}’);
new Ajax.InPlaceEditor(’email’, ‘ajax.php?m=optsave&type=email&id={$user['id']}’);
</script>
<h2>Password Control</h2>
<p>In order to edit your password, you must first verify your current one, then enter your new one:</p>
<form name=’password_reset’>
Current Password: <input type=’password’ id=’current_password’ /><br />
New Password: <input type=’password’ id=’new_password’ /><br />
Confirm New Password: <input type=’password’ id=’new_password_confirm’ /><br />
<input type=’button’ value=’change password’ onclick=’password()’ id=’change_password’ /></form>
<div id=’password_status’></div>”
;
}
}
?>

You should be able to understand all of this, we’re just sticking a few variables here and there, nothing major. Next we’re going to make our JavaScript and HTML.

File: index.php

 

<html>
<head>
<title><?php echo $title; ?></title>
<!– Include the scriptaculous library –>
<script src=‘../scriptaculous/prototype.js’></script>
<script src=‘../scriptaculous/scriptaculous.js’></script>
<script type=‘text/javascript’>
function password()
{
//Typing skils. . .
if($F(‘new_password_confirm’) !== $F(‘new_password’))
{
alert(“Please make sure both your new passwords match!”);
$(‘new_password’).focus();
return;
}
else if($F(‘new_password_confirm’) == || $F(‘new_password’) == || $F(‘current_password’) == )
{
alert(“Please fill in all fields.”);
$(‘current_password’).focus();
}
else
{
//construct the ajax request
//$F() gets the field with the given id’s value
var opt = {
method:‘post’,
postBody:‘m=pwd&current=’ + $F(‘current_password’) + ‘&new=’ + $F(‘new_password’) + ‘&id=<?php echo $user['username']; ?>’,
onSuccess: function(t) { $(‘password_status’).innerHTML = t.responseText; $(‘change_password’).disabled = false; },
onLoading: function() { $(‘login_button’).value = ‘Working’; $(‘change_password’).disabled = true; }
}
//send request to the ajax.php
new Ajax.Request(‘ajax.php’, opt);
}
}
</script>
</head>
<body>
<?php echo $con, $footer; ?>
</body>
</html>

Hoorah, the settings manager is totally complete. Now we just need to do the private messaging system. Our only use of AJAX there will be to delete messages, becuase it’s totally worthless to have to reload your inbox to delete one lousy message. The top of the script will use the MIN_AUTH_LEVEL constant, becuase we don’t want guests trying to access inboxes! We set the auth level to 1, meaning only users + admins.

File: pm.php

 

<?php
session_start();
define(‘MIN_AUTH_LEVEL’, ‘1′);
include(‘./config.php’);
$footer = “<a href=’index.php’>Home</a> – <a href=’?do=’>Inbox</a> – <a href=’?do=send’>Send New PM</a> – <a href=’login.php?do=logout’>Logout</a>”;

Note how the min auth level is declared before we include the config file, if it’s not, it won’t work. Let’s work on the inbox.

File: pm.php

 

if($_GET['do'] == )
{
$title = “PM Inbox”;
//Fetch an associative array of the user’s PMs
$pms = listpms($user['username']);
//Notice from send new PM page
if($notice)
{
$con .= “<strong>$notice</strong>”;
}
//Begin the PM inbox
$con .= “<h2>PM Inbox</h2>
<p>Clicking the delete icon permanetly deletes the message! Click on the title to view the full message.</p>
<table border=’1′>
<tr><th>Title</th><th>From</th><th>Delete</th></tr>”
;
//For the unpopular, a no PM message so the table looks decent
if(count($pms) == 0)
{
$con .= “<tr><td colspan=\”3\”><strong>Sorry, you have no PM’s.</strong></td></tr>”;
}
else
{
//Cycle through every PM, $v will store an associative array of every PM’s details
foreach($pms as $v)
{
//Delete_pm starts an AJAX request to delete the PM
$con .= “<tr id=\”pm_{$v['id']}\”><td><a href=’?do=view&id={$v['id']}’>{$v['title']}</a></td><td>{$v['from']}</td><td align=’center’><a href=’#’ onclick=\”delete_pm(’{$v['id']}’, ‘{$v['title']}’, false);\”><img src=\”./images/delete.png\” style=\”border:none;\” /></a></tr>”;
}
}
$con .= “</table>”;
}

Nothing earth shattering there either, our handy function gets every PM for us in a nice array that we can easily cycle through. Next we have to handle viewing PM’s. . . oh no!

File: pm.php

 

else if($_GET['do'] == ‘view’)
{
$footer = “<a href=’index.php’>Home</a> – <a href=’pm.php’>Inbox</a>”;
//Single array of a PM
$pm = get_pm($_GET['id']);
//get_pm checked ownership of the PM, it’s not the current users
if(!$pm)
{
$con = “You are not authorized to view this PM!”;
}
else
{
//Mark this PM as read
mark_read($pm['id']);
//Display the message from the pm array
//The reply form will toggle up and down using a scriptaculous effect (a pretty one!)
$con = “<h2>{$pm['title']}</h2>
<p>From: {$pm['from']}<br />
{$pm['message']}<br /><a href=’#’ onclick=’reply();’>Reply</a> – <a href=’#’ onclick=\”delete_pm(’{$pm['id']}’, ‘{$pm['title']}’, true);\”>Delete</a></p>
<div id=’reply’ style=’display:none;’>
<h3>Reply:</h3>
<form method=’post’ action=’?do=send’>
To: <input type=’text’ name=’to’ value=’{$pm['from']}’ /><br /><br />
Title: <input type=’text’ name=’title’ value=’Re: {$pm['title']}’ /><br /><br />
Message: <br />
<textarea rows=’10′ cols=’50′ name=’message’></textarea><br /><br />
<input type=’submit’ value=’Send!’ name=’send’ /></form>
</div>”
;
}
$title = “View PM”;
}

Lastly, we’ve got to be able to send messages, otherwise it’s useless! In this section, we make use of our notice variable.

File: pm.php

 

else if($_GET['do'] == ’send’)
{
//We’re sending
if($_POST['send'])
{
//attempt to send the PM
if(sendpm($user['username'], $_POST['to'], $_POST['title'], $_POST['message']))
{
//Display notice at inbox
$notice = “PM Sent”;
}
else
{
//same as above
$notice = “PM Couldn’t Be Sent!”;
}
//Back to the inbox to see the notice
header(“Location: pm.php”);
}
//Display the form
else
{
$title = “Send PM”;
$con = “<h2>Send New PM</h2>
<form method=’post’ action=’?do=send’>
To: <input type=’text’ name=’to’ /><br /><br />
Title: <input type=’text’ name=’title’ /><br /><br />
Message: <br />
<textarea rows=’10′ cols=’50′ name=’message’></textarea><br /><br />
<input type=’submit’ value=’Send!’ name=’send’ /></form>”
;
}
}
?>

Let’s get our last HTML + JavaScript for this part out of the way.

File: pm.php

 

<html>
<head>
<title><?php echo $title; ?></title>
<script src=‘../scriptaculous/prototype.js’></script>
<script src=‘../scriptaculous/scriptaculous.js’></script>
<script type=‘text/javascript’>
//Delete via AJAX
function delete_pm(pmid, pmtitle, redir)
{
if(confirm(“Are you sure you want to delete the message titled “ + pmtitle))
{
var opt = {
method:‘post’,
postBody:‘m=delpm&password=<?php echo $user['password']; ?>&id=’ + pmid + ‘&uid=<?php echo $user['username']; ?>’,
onSuccess: function(t) { handle_delete(t, pmid, redir); }
}
new Ajax.Request(‘ajax.php’, opt);
}
}

//Toggle reply form with a fancy effect
function reply()
{
if(!Element.visible(‘reply’))
{
Effect.SlideDown(‘reply’);
}
else
{
Effect.SlideUp(‘reply’);
}
}

//Either redirect to the inbox, or remove the table row of that PM
function handle_delete(t, pmid, redir)
{
if(t.responseText == “0″)
{
alert(“The PM could not be deleted! This may be a systems error, so please try again.”);
}
else
{
if(redir)
{
window.location = ‘pm.php’;
}
else
{
new Effect.Fade(‘pm_’ + pmid);
}
}
}
</script>
</head>
<body>
<?php echo $con, $footer; ?>
</body>
</html>

That’s the end of part 2. As you can see, most of the code was just determining what needed to be done and sending messages to the user. Becuase of our backend, we really only have to call one or two functions to get what we need, or to protect a page from guests. There’s no more stuff user-end in this tutorial, part 3 will cover only one thing, a simply admin panel to modify user’s data. At the end of part 3, an example will be put up.

Download all the script files in an unique .zip archive here

Member Managment System Using PHP, AJAX – Part 1

One of the most common request of people learning PHP is that they want to make a member system thing. That’s what we’re going to do, only cooler. I’m going to try and teach you some basic concepts of JavaScript and PHP so that you can take this code and make it a hundred times better by adding new features.

The tutorial isn’t meant to be pretty, except for the JavaScript effects. I don’t use much color, and it’s standard yucky formatting. It’s your job to make it look nice.

The tutorial will cover setting up the database, and making basic front and backends. The features are:

  • Setting up the database, backend (Part 1)
  • Registering with E-mail verification (Part 1)
  • Logging in and out (Part 1)
  • Private Messaging (Part 2)
  • Changing password, E-mail, and name (Part 2)
  • Simple admin area to modify + delete users (Part 3)

Before we start to code, we need to design how our system is going to work. The configuration file will be the core, do-everything file. It connects to the database, includes the necesscary file, gets a users details, and makes sure the user can view whatever page they are at. The included file will store all of our functions, these functions perform things such as logging in, registering, sending PM’s, or modifying user’s details.

We will have global variable, this will be $user. $user will be loaded by the config file, and will store the current users details. If the user is a guest, it will have dummy data. $user is an array and can be used anywhere as long as the config file was included.

Protecting pages is also easy. There is a small permissions system in place, there are 4 levels. -1 = non-activated user, 0 = guest, 1 = user, and 2 = admin. This permission level is stored in $user under the name admin. Our config file will check for a constant called MIN_AUTH_LEVEL, if it exists, it will compare the user’s level to the MIN_AUTH_LEVEL. If the user’s auth level is to low, they get a error, otherwise they see the content. This makes it easy to protect pages from guests and protect the admin panel.

Enough talk, you should get how the system will work, now let’s set up the database. We’re going to require three tables, one for the PM’s, one for the user’s, and one for the activation keys.

 

CREATE TABLE `keys` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`key` varchar(32) NOT NULL DEFAULT ,
PRIMARY KEY (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1CREATE TABLE `messages` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`from` varchar(255) NOT NULL DEFAULT ‘0′,
`to` varchar(255) NOT NULL DEFAULT ‘0′,
`message` longtext NOT NULL,
`title` varchar(255) NOT NULL DEFAULT ,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`read` int(1) NOT NULL DEFAULT ‘0′,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1

CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL DEFAULT ,
`password` varchar(32) NOT NULL DEFAULT ,
`name` varchar(255) NOT NULL DEFAULT ,
`email` varchar(255) NOT NULL DEFAULT ,
`ip` varchar(255) NOT NULL DEFAULT ,
`admin` int(1) NOT NULL DEFAULT ‘0′,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1

Now that we have the tables set up, we can create our config file. As we said earlier, this file will contain database information, get user information, and check permissions. This file is not meant to be accesed directly, it will be included by other files (like login, index, etc.) You might want to read up on constants and the ternary operator.

File: config.php

 

<?php
//Database
define(‘DB_HOST’, ‘localhost’);
define(‘DB_USER’, ‘root’);
define(‘DB_PASS’, );
define(‘DB_NAME’, ‘members’);
mysql_connect(DB_HOST, DB_USER, DB_PASS);
mysql_select_db(DB_NAME);//Site URL + Name
define(‘SITE_URL’, ‘http://site.com’);
define(‘EMAIL_URL’, ’site.com’);
define(‘SITE_NAME’, ‘YourSite’);

//Include functions
if(!@include(“./member-functions.php”))
{
include(“../member-functions.php”);
}

//Userdata
$username = (@$_SESSION['username']) ? @$_SESSION['username'] : @$_COOKIE['username'];
$password = (@$_SESSION['password']) ? @$_SESSION['password'] : @$_COOKIE['password'];
$user = userdata($username, $password);

//Activation Checks
if($user['admin'] == ‘-1′ && !defined(‘REQUIRE_ACTIVATION’))
{
die(“Sorry, this account has not been activated. Upon registration, we sent an E-mail to {$user['email']} containing a link that activates your account.”);
}

//Auth Check
if(defined(‘MIN_AUTH_LEVEL’))
{
if(MIN_AUTH_LEVEL > $user['admin'])
{
die(“You are trying to view a page you do not have permission to view! If you think this is an error, try <a href=’”. SITE_URL .“login.php’>logging in</a>. This page may require <a href=’”. SITE_URL .“login.php?do=reg’>registration</a> in order to view.”);
}
}
?>

Yea, that’s a lot of code, but it does just what we said, so you should be able to understand it quite easily. You may be wondering about the userdata() function, no, it’s not a standard PHP function, but it’s one declared in member-functions.php. This function returns an array of the user’s details, which go into $user.

Next we’re going to look at member-functions.php, there is still no UI here, just PHP. It’s a lot of code, even in chunks. I’ve seperated it into three categories: user functions, PM functions, and just general functions. First is the user functions, these will login, logout, register, modify details. The register function needs its own explanation simply becuase it’s a little more complicated than the rest.

File: member-functions.php

 

function register($username, $password, $email, $ip, $name, $admin = 0)
{
if(empty($username) || empty($password) || empty($email) || empty($name) || strlen($password) < 6)
{
$return = ‘0|Please complete <strong>all</strong> fields and ensure your password is atleast six characters in length!’;
}
else
{
$query = mysql_query(“INSERT INTO `users` (`username`, `password`, `name`, `email`, `ip`, `admin`) VALUES (’$username’, ‘”. md5($password) .“‘, ‘$name’, ‘$email’, ‘”. $_SERVER['REMOTE_ADDR'] .“‘, ‘-1′)”);
if($query)
{
//last inserted ID
$id = mysql_insert_id();
//Generate MD5 hash key
$key = generate_key(6);
//Put together the key string
$key_string = “key=$key&id=$id”;
//Insert into database
$query = mysql_query(“INSERT INTO `keys` (`user_id` , `key`) VALUES (’$id’, ‘$key’)”);
//Send account activation E-mail
mail($email, ‘Account Activation at’. SITE_NAME, “Please click the following link to activate your account:\n——–\n. SITE_URL .“activate.php?”. $key_string, “From: staff@”. EMAIL_URL);
$return = ‘1|Thank you for registering at ‘. SITE_NAME .‘! In order for your account to become active, you must verify your E-mail address. We have sent you an E-mail to ‘. $email .‘ containing a link to activate your account. Once clicked, your account will be activated.(’. $key_string .‘)’;
}
else
{
$return = ‘0|An error occured during your registration process, please retry in a minute or two as it could simply be a systems glitch.(’. mysql_error() .‘)’;
}
}
return $return;
}//Checks if a given field in the users table is taken
function is_taken($field, $value)
{
$query = mysql_query(“SELECT `id` FROM `users` WHERE `$field` = ‘$value’”);
if(mysql_num_rows($query) > 0)
{
return true;
}
else
{
return false;
}
}

//Checks user + pass, then logs in
function login($username, $password, $cookie = true)
{
if(check_login($username, $password))
{
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
if($cookie)
{
//Sets cookies
setcookie(‘username’, $username, time()+15000);
setcookie(‘password’, $password, time()+15000);
}
return true;
}
else
{
return false;
}
}

//Checks login details
function check_login($username, $password)
{
$query = mysql_query(“SELECT `id` FROM `users` WHERE `username` = ‘$username’ AND `password` = ‘$password’”) or die(mysql_error());
if(mysql_num_rows($query) > 0)
{
return true;
}
else
{
return false;
}
}

//Destroy all sessions and cookies
function logout()
{
session_destroy();
setcookie(‘username’, $username, time()-15000);
setcookie(‘password’, $password, time()-15000);
return true;
}

//Updates a users details in the database
function edit_user($id, $username, $name, $email, $admin)
{
$query = mysql_query(“UPDATE `users` SET `username` = ‘$username’, `name` = ‘$name’, `email` = ‘$email’, `admin` = ‘$admin’ WHERE `id` = ‘$id’”);
if($query)
{
return true;
}
else
{
return false;
}
}

//Remove user from database
function delete_user($id)
{
$query = mysql_query(“DELETE FROM `users` WHERE `id` = ‘$id’”);
if($query)
{
return true;
}
else
{
return false;
}
}

//Gets an array of all user data from the database
function userdata($id, $pass)
{
if(!check_login($id, $pass))
{
//Fill array with guest data
$user = array(‘id’ => ‘0′, ‘username’ => ‘Guest’, ‘password’ => , ‘name’ => ‘Guest’, ‘email’ => , ‘ip’ => $_SERVER['REMOTE_ADDR'], ‘admin’ => ‘0′);
}
else
{
$query = mysql_query(“SELECT `username`, `password`, `name`, `email`, `ip`, `admin`, `id` FROM `users` WHERE `username` = ‘$id’”);
$r = mysql_fetch_row($query);
$user = array(‘id’ => $r[6], ‘username’ => $r[0], ‘password’ => $r[1], ‘name’ => $r[2], ‘email’ => $r[3], ‘ip’ => $r[4], ‘admin’ => $r[5]);
}
return $user;
}

Please, read the comments to understand the code, that’s what they’re there for. You’ll see the generate_key() function later on, it basically generates a unique key for, how complex! :P Next up is the PM functions. This really only consists of SELECT’s, INSERT’s, and DELETE’s. Nothing to hard here, we just have to remember to maintain ownership of PM’s.

File: member-functions.php (continued)

 

//Inserts PM into database
function sendpm($fid, $tid, $title, $message)
{
if(mysql_query(“INSERT INTO `messages` (`from`, `to`, `message`, `title`) VALUES (’$fid’, ‘$tid’, ‘”. htmlspecialchars($message) .“‘, ‘”. htmlspecialchars($title) .“‘)”))
{
return true;
}
else
{
return false;
}
}//Counts number of unread PM’s
function count_unread($uid)
{
$query = mysql_query(“SELECT COUNT(*) FROM `messages` WHERE `to` = ‘$uid’ AND `read` = ‘0′”) or die(mysql_error());
$r = mysql_fetch_row($query);
return $r[0];
}

//Marks a PM as read
function mark_read($id)
{
$query = mysql_query(“UPDATE `messages` SET `read` = ‘1′ WHERE `id` = ‘$id’”);
}

//Delete’s a PM
function delete_pm($id, $uid, $password)
{
global $user;
if($user['password'] == $password)
{
//Make sure to check it’s theirs
$query = mysql_query(“DELETE FROM `messages` WHERE `id` = ‘$id’ AND `to` = ‘$uid’”) or die(mysql_error());
return true;
}
else
{
return false;
}
}

//Fetches a PM, checks owner, returns array
function get_pm($id)
{
global $user;
$query = mysql_query(“SELECT * FROM `messages` WHERE `id` = ‘$id’”);
$pm = mysql_fetch_assoc($query);
if($pm['to'] !== $user['username'])
{
return false;
}
else
{
return $pm;
}
}

//Get all PM’s for a user
function listpms($uid)
{
$pms = array();
$query = mysql_query(“SELECT * FROM `messages` WHERE `to` = ‘$uid’ ORDER BY `time` DESC”);
while($r = mysql_fetch_assoc($query))
{
$pms[$r['id']] = array(‘id’ => $r['id'], ‘to’ => $uid, ‘from’ => $r['from'], ‘title’ => $r['title'], ‘message’ => $r['message']);
}
return $pms;
}

Last up are a few AJAX-related functions that just done one tiny job. Very easy to understand.

File: member-functions.php (continued)

 

function edit_name($name, $id)
{
$query = mysql_query(“UPDATE `users` SET `name` = ‘$name’ WHERE `id` = ‘$id’”);
return true;
}//Edit only the E-Mail (AJAX)
function edit_email($email, $id)
{
$query = mysql_query(“UPDATE `users` SET `email` = ‘$email’ WHERE `id` = ‘$id’”);
return true;
}

//Edit only the password (AJAX)
function edit_password($password, $id)
{
//check hash
if(strlen($password) !== 32)
{
$password = md5($password);
}
$query = mysql_query(“UPDATE `users` SET `password` = ‘$password’ WHERE `id` = ‘$id’”);
if($query)
{
$_SESSION['password'] = $password;
$_COOKIE['password'] = $password;
return true;
}
else
{
return false;
}
}

Woops, almost forget our 3 utility/general/whatever functions. These are there to generate the key, list all users, and count the number of entries in a table.

File: member-functions.php

 

//Generates key x long, md5’s it
function generate_key($length)
{
return(md5(substr(str_shuffle(‘qwertyuiopasdfghjklmnbvcxz0987612345′), 0, $length)));
}//Get every user
function list_all_users()
{
$query = mysql_query(“SELECT * FROM `users`”);
$users = array();
while($r = mysql_fetch_assoc($query))
{
$users[$r['id']] = $r;
}
return $users;
}

//Get a count of the entries in a given table
function count_tbl($tbl)
{
$query = mysql_query(“SELECT COUNT(*) FROM `$tbl`”);
$r = mysql_fetch_row($query);
return $r[0];
}

The last part of the backend is the AJAX handler, it receives the requests from the scripts and handles them. Should be easy to get. If you’re wondering what $_POST['m'] is, it stands for method. Or, what are we going to do? Edit the password, update the user, delete a PM. . . We’ll call our functions created earlier to make everything easy

File: ajax.php

 

<?php
session_start();
//Load up database, functions, user info
include(‘./config.php’);if(@$_POST['m'] == ‘login’)
{
if(login($_POST['username'], md5($_POST['password'])))
{ //success
echo “1″;
}
else
{ //failure hmph
echo “0″;
}
}
//in place editor is GET
else if(@$_GET['m'] == ‘optsave’)
{
if($_GET['type'] == ‘email’)
{
edit_email($_POST['value'], $_GET['id']);
}
else
{
edit_name($_POST['value'], $_GET['id']);
}
//AJAX will update field to this value
echo $_POST['value'];
}
else if($_POST['m'] == ‘pwd’)
{
if(md5($_POST['current']) == $user['password'])
{
if(edit_password(md5($_POST['new']), $_POST['id']))
{ //success
echo “Thanks, your password has been updated!”;
}
else
{ //hmm
echo “An error occured when changing your password, please try again.”;
}
}
else
{ //little shady :)
echo “The password you provided does not match your current password, please try again.”;
}
}
else if($_POST['m'] == ‘check’)
{
//Checks username/email in the DB
if(is_taken($_POST['type'], $_POST['value']))
{ //sucess
echo “0″;
}
else
{ //failure
echo “1″;
}
}
else if($_POST['m'] == ‘reg’)
{
$reg = register($_POST['username'], $_POST['password'], $_POST['email'], $_SERVER['REMOTE_ADDR'], $_POST['name']);
echo $reg; //Give the registration message (error/success)
}
else if($_POST['m'] == ‘delpm’)
{
if(delete_pm($_POST['id'], $_POST['uid'], $_POST['password']))
{//sucess
echo “1″;
}
else
{ //failure
echo “0″;
}
}
else if($_POST['m'] == ‘deluser’)
{
if($user['password'] == $_POST['password'] && $user['admin'] == ‘2′)
{
if(delete_user($_POST['id']))
{ //sucess
echo “1″;
}
else
{ //failure
echo “0″;
}
}
}

//Edit users
else if($_POST['m'] == ‘edituser’)
{
//Ensure user is admin
if($user['password'] == $_POST['password'] && $user['admin'] == ‘2′)
{
if(edit_user($_POST['id'], $_POST['username'], $_POST['name'], $_POST['email'], $_POST['auth']))
{ //sucess
echo “1″;
}
else
{ //failure
echo “0″;
}
}
}
?>

Finally, we can start the frontend! :D We’re going to start with the login, and break it up into two parts. The PHP and JavaScript. First is the JavaScript, which will send out requests to login, and register.
Logging In JavaScript:

File: login.php | JavaScript code

 

function login()
{
if($F(‘password’) == || $F(‘username’) == )
{
alert(“Please fill in all fields before submitting.”);
return;
}
//AJAX request options
var opt = {
method:‘post’,
postBody:‘m=login&username=’ + $F(‘username’) + ‘&password=’ + $F(‘password’),
onSuccess: function(t) { /* check on success */ checkLogin(t); },
onLoading: function() { /* Disable login button with message */$(‘login_button’).value = ‘Authencating’; $(‘login_button’).disabled = true; }
}
//Send request
new Ajax.Request(‘ajax.php’, opt);
}

function checkLogin(t)
{ //t object is automatically passed
if(t.responseText == “1″)
{
//Show main screen
window.location = ‘index.php’;
}
else
{
//Give a error message, reenable login button
$(‘response’).innerHTML = ‘<strong>Authencation Failed!</strong>’;
Element.show(‘response’);
$(‘login_button’).value = ‘Login’;
$(‘login_button’).disabled = false;
}
}

We’re sending the request to our AJAX handler, and having the function checkLogin() handle the results of that. Either show us the main page, or give an error. The next part is a little more complicated, because we do the same thing, and add something that goes and checks if a username/email is already existant. If it is, the box will be highlighted red!

 

function check_value(var_n, field_n)
{
var opt = {
method:‘post’,
postBody:‘m=check&type=’ + var_n + ‘&value=’ + $F(field_n),
onSuccess: function (t) { update_check(t, field_n); },
onLoading: function() {}
}
new Ajax.Request(‘ajax.php’, opt);
}

function update_check(t, field_n)
{
if(t.responseText == “0″)
{
//The name already exists, show message
$(field_n + ‘_check’).innerHTML = ‘<img src=”./images/error-small.png” /> That already exists!’;
$(field_n).style.border = ‘1px red solid’;
$(field_n).focus();
}
else
{
//Good to go!
$(field_n + ‘_check’).innerHTML = ;
$(field_n).style.border = ‘1px green solid’;
}
}
function register()
{
//Basic error checking
if($F(‘email’) == || $F(‘name’) == || $F(‘confirm_password’) == || $F(‘password’) == || $F(‘username’) == )
{
alert(“Please fill in all fields.”);
return;
}
else if($F(‘password’) !== $F(‘confirm_password’))
{
alert(“Please ensure your passwords match!”);
$F(‘confirm_password’).focus();
}
else
{
//Construct the AJAX object, add all form fields in the register_form to the paramaters
var opt = {
method:‘post’,
postBody:‘m=reg&’ + Form.serialize(‘register_form’),
onSuccess: function(t) { $(‘register_button’).value = “register”; $(‘register_button’).disabled = false; handle_register(t); },
onLoading: function() { $(‘register_button’).value = “Working…”; $(‘register_button’).disabled = true; }
}
new Ajax.Request(‘ajax.php’, opt);
}
}

function handle_register(t)
{
var data = t.responseText.split(“|”);
//Give either the success or error message.
if(data[0] == “0″)
{
$(‘register_message’).innerHTML = data[1];
}
else
{
$(‘register_main’).innerHTML = data[1];
}
}
</script>
</head>
<body>
<?php echo $con; ?>
</body>
</html>
<?php
ob_end_flush();
?>

Now we can move on to the PHP part. Note: This goes before the JavaScript code! We’ll use the $_GET['do'] variable to determine what exactly to do (hehe).

File: login.php | PHP Code

 

ob_start();
session_start();
include(‘./config.php’);
if($_GET['do'] == || $_GET['do'] == ‘login’)
{
if($user['username'] == ‘Guest’)
{
$con = ‘<h2>Login</h2>
<form name=”login_form”>
Username: <input type=”text” id=”username” /><br /><br />
Password: <input type=”password” id=”password” /><br /><br />
<input id=”login_button” type=”button” onclick=”login();” value=”Login” /></form>
<div id=”response” style=”display:none;”></div>
<a href=”?do=reg”>Register Here</a>’
;
$title = ‘Login’;
}
else
{
$con = “<h2>Error</h2>
<p>Looks like you’re already logged in. Did you want to <a href=’?do=logout’>logout</a>?”
;
$title = “Erorr”;
}
$footer = “<p><a href=’index.php’>Home</a> – <a href=’login.php?do=reg’>Register</a></p>”;
}

The $con, $title, and $footer variables will be placed in the HTML at the end of the file, you’ll see. Simple, show login form, or an error, saying you’re already logged in. Logging out is rather simple. :)

 

else if($_GET['do'] == ‘logout’)
{
logout();
$con = “<h2>Logged Out</h2>
<p>All cookies have been cleared and you were sucessfully logged out of our systems.”
;
$title = “Logged Out”;
$footer = “<p><a href=’login.php’>Login</a>”;
}

Oh yea, did I lose you? :P Last, but certainly not least, is the registration form. Nothing but some HTML. :)

 

else if($_GET['do'] == ‘reg’)
{
$con = ‘<h2>Register</h2>
<div id=”register_main”>
<form id=”register_form”>
Desired Username: <input type=”text” name=”username” onblur=”check_value(\’username\’, \’username\’);” id=”username” /><span id=”username_check”></span><br /><br />
Password: <input type=”password” name=”password” id=”password” /><br /><br />
Confirm Password: <input type=”password” name=”confirm_password” id=”confirm_password” /><br /><br />
E-Mail Address: <input type=”text” name=”email” onblur=”check_value(\’email\’, \’email\’);” id=”email” /> <span id=”email_check”></span><br /><br />
Name (first only): <input type=”text” name=”name” id=”name” /><br /><br />
<input type=”button” id=”register_button” value=”register” onclick=”register();” /></form></div>
<div id=”register_message” style=”color:red; font-weight:bold;”></div>
<em>All fields are required – Confirmation sent to E-mail address</em>’
;
$title = “Register”;
$footer = “<p><a href=’login.php’>Login</a>”;
}

Now we’re going to finish part 1 with the registration activation script, this is pretty simple, just check if the key exists, if it does, update the user to active.

 

<?php
define(‘REQUIRE_ACTIVATION’, false);
include(‘./config.php’);
$key = $_GET['key'];
$id = $_GET['id'];
$query = mysql_query(“SELECT * FROM `keys` WHERE `key` = ‘$key’ AND `user_id` = ‘$id’”);
if(mysql_num_rows($query) > 0)
{
//Key exists.
mysql_query(“UPDATE `users` SET `admin` = ‘1′ WHERE `id` = ‘$id’”);
$con = “<h2>Activated</h2>
<p>Thanks, your account has been fully activated. You may now proceed to <a href=’login.php’>login</a>.</p>”
;
$title = “Account Activated”;
}
else
{
$con = “<h2>Error</h2>
<p>Uh-oh! The key and ID you provided us are incorrect, please go back and check your confirmation E-mail.”
;
$title = “Activation Error”;
}
?><html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>
<?php echo $con, $footer; ?>
</body>
</html>

This concludes part 1. A quick recap, we setup our database, config file, and the backend functions. We also set up the logging in, out, and registration parts of things. All that’s left is the settings manager, PM system, and admin backend. There are 2 more parts.

Download all the script files in an unique .zip archive here