If you're new here, you may want to subscribe to my RSS feed. So that you can read the latest updates about Web2.0 tools, Making Money Online, Tips in SEO, Ajax and many more. Thanks for visiting ProgramimiCOM!
A common knew feature that most web 2.0 sites are using these days is double-click editing. I’m not sure if there’s actually a technical term for it, however, that’s what I like to call it. What I’m referring to is how some sites have static text areas such as divs or cells which when clicked or double-clicked instantly become an editable text box. This is not very difficult to do, and is very nice when you want to have a page displaying information very professionally but still giving your user the ability to edit it quickly and easily.
First of all here is some simple javascript that would go in your page header
text = new Array(); //This array will hold variables to tell the script the state that it should switch tofunction switchState(id)
{
content = ”; //Nullify the content variable
if( text[id] != 1 ) //Check if text[’id’] is set to 1 (explained later)
{
content = document.getElementById(‘child’ + id).innerHTML; //Define content as the inner content of the div
new_html = ‘<input type=”text” id=”child’ + id + ‘” value=”‘ + content + ‘” />’; //Define the new HTML (textbox)
document.getElementById(‘parent’ + id).innerHTML = new_html; //Set the parent div’s HTML to the new HTML
text[id] = 1; //We set this variable for the script to remember that we already set it to a text box
}
else
{
//So with this case we will be doing the opposite and switching back to a div
content = document.getElementById(‘child’ + id).value; //Define content as the value of the textbox
new_html = ‘<div id=”child’ + id + ‘”>’ + content + ‘</div>’; //Define the new HTML (div)
document.getElementById(‘parent’ + id).innerHTML = new_html; //Set the parent div’s HTML to the new HTML
text[id] = 0; //We set this variable for the script to remember that we have set it back to a div
}
}
Most of this script is explained in the comments, and what it basically does is determines the current state of the div/textbox then takes the content out of the div/textbox and puts it into a new div/textbox.
I will now show you the basic HTML structure to make this work.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=“http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=“Content-Type” content=“text/html; charset=UTF-8″ />
<title>The amazing transforming div/textbox!</title><script language=“javascript” type=“text/javascript”>
text = new Array(); //This array will hold variables to tell the script the state that it should switch to
function switchState(id)
{
content = ”; //Nullify the content variable
if( text[id] != 1 ) //Check if text[’id’] is set to 1 (explained later)
{
content = document.getElementById(‘child’ + id).innerHTML; //Define content as the inner content of the div
new_html = ‘<input type=”text” id=”child’ + id + ‘” value=”‘ + content + ‘” />’; //Define the new HTML (textbox)
document.getElementById(‘parent’ + id).innerHTML = new_html; //Set the parent div’s HTML to the new HTML
text[id] = 1; //We set this variable for the script to remember that we already set it to a text box
}
else
{
//So with this case we will be doing the opposite and switching back to a div
content = document.getElementById(‘child’ + id).value; //Define content as the value of the textbox
new_html = ‘<div id=”child’ + id + ‘”>’ + content + ‘</div>’; //Define the new HTML (div)
document.getElementById(‘parent’ + id).innerHTML = new_html; //Set the parent div’s HTML to the new HTML
text[id] = 0; //We set this variable for the script to remember that we have set it back to a div
}
}
</script>
</head>
<body>
<div id=“parent1″ ondblclick=“javascript:switchState(1)”>
<div id=“child1″>Some text</div>
</div>
<div id=“parent2″ ondblclick=“javascript:switchState(2)”>
<div id=“child2″>Some more text</div>
</div>
</body>
</html>
As you can see it’s very simple to setup, and very simple to use. Just double click on the text to transform it into a textbox, then double click it again to transform it back!
One annoying thing about many of the “old-fashioned” style polls which most sites still use is that you must reload an entire page just to submit one little vote. This can be time consuming for people on limited bandwidth, or on sites that it would just be plain impractical to reload the content.
First of all this tutorial will not teach the underlying concepts of AJAX, merely show you how to use it specifically. If you are looking to learn how to use AJAX I suggest you read the tutorial “Retrieving database information with AJAX, PHP and MySQL”.
To begin with, we’ll set up two MySQL tables: results, and ips. Here are the MySQL queries for both:
CREATE TABLE `results` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`option` varchar(255) NOT NULL,
`count` bigint(20) NOT NULL DEFAULT ‘0′,
KEY `id` (`id`)
)
CREATE TABLE `ips` (
`ip` VARCHAR( 255 ) NOT NULL ,
`time` INT NOT NULL
)
The first table “results” has three fields, id, option, and count. Id is simple for identification purposes, option is the name of the option in question, and count is the amount of votes that option received. Each option you wish to have in your poll would have its own row in that table. Further down you will find a simple script to administrate your poll.
Next we need a file that will be accessed by AJAX to add a vote, and retrieve the total votes. This will use PHP to query our mysql tables.
<?php//We’ll call this file vote.php
$id = $_GET[‘id’]; //This is the id of the option the user voted for retrieved through GET
mysql_connect(“localhost”, “mysql_user”, “mysql_password”); //Connect to the MySQL server with your host (probably localhost), your mysql username, and your mysql password
mysql_select_db(“mysql_db”); //Select your MySQL database by name
$ip = $_SERVER[‘REMOTE_ADDR’]; //The user’s IP address
$query = mysql_query(“SELECT * FROM ips WHERE ip = ‘$ip’”) or die(“n”); //Query to see if there is already a submission from that IP
if( mysql_num_rows($query) ) //If there has been a submission by that IP already…
{
die(“n”); //End the script and print out “n”
}
$query = mysql_query(“SELECT * FROM results WHERE id = $id”) or die(“n”); //Select the row (option) with the same id as the voteID
if( mysql_num_rows($query) == 1 ) //If there is 1 row found with that id…
{
mysql_query(“UPDATE results SET count = count + 1 WHERE id = $id”) or die(“n”); //Update the row to add 1 to the count field
mysql_query(“INSERT INTO ips (ip, time) VALUES (’$ip’, “. time(). “)”) or die(“n”); //Insert the user’s IP into the database so they can’t vote again
$query2 = mysql_query(“SELECT * FROM results WHERE id = $id”) or die(“n”); //Same as original query to get the new value of count
if( mysql_num_rows($query2) == 1 ) //If there is 1 row found with that id…
{
$row = mysql_fetch_assoc($query2); //Use $row as the associative fetching key
$count = $row[‘count’]; //$count is now the value of the count field for the option’s row
}
$updated = “y”; //If we got to here, it means that the row has been updated so we set this variable to “y” which will be echoed out to tell our AJAX script whether or not it worked
}
else
{
$updated = “n”; //Same deal except this would only be gotten to if we did not successfully update so it’s set to “n”
}
echo $updated. $count; //Echo out “y” or “n” and the new count
?>
As I’m sure you can gather from the comments this script the goal is to add one vote to the option the user has voted for, then retrieve the new amount of votes for that option. The final result is either going to be “n” or “y#” (# representing the new amount of votes). The only way the output would be “n” would be if the user somehow voted for something that didn’t exist, there was a database error, or they previously had voted.
We now have all the server-side coding complete for the updating and retrieving, so now we need to get the AJAX setup so that these can be used. This is the JavaScript that will be on the page that contains the poll.
function vote(id){
var xmlhttp=false; //Clear our fetching variable
try {
xmlhttp = new ActiveXObject(‘Msxml2.XMLHTTP’); //Try the first kind of active x object…
} catch (e) {
try {
xmlhttp = new
ActiveXObject(‘Microsoft.XMLHTTP’); //Try the second kind of active x object
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!=‘undefined’) {
xmlhttp = new XMLHttpRequest(); //If we were able to get a working active x object, start an XMLHttpRequest
}
var file = ‘vote.php?id=’; //This is the path to the file we just finished making
xmlhttp.open(‘GET’, file + id, true); //Open the file through GET, and add the id we want to retrieve as a GET variable
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) { //Check if it is ready to recieve data
var content = xmlhttp.responseText; //The content data which has been retrieved
if( content != ‘n’ ){ //If the response was not “n” (meaning it worked)
content = content.replace(‘y’, ”); //Get rid of the y infront of our result *
document.getElementById(‘option’ + id).innerHTML = content; //Set the inner HTML of the div with the old value in it to the new value **
}
}
}
xmlhttp.send(null) //Nullify the XMLHttpRequest
return;
}
As you can see it is not very different compared to simple retrieval, because most of what we are doing is server-side. I only have two things I wanted to explain further, marked by the stars by their comments.
*
content = content.replace(‘y’, ”);
I just starred this to make sure that everyone could understand what was going on. If we got to this stage in the script, it means that we would get a result that looked like “y#”, when all we wanted was the “#”. This just replaces the “y” with nothing so that only the number remains.
**
document.getElementById(‘option’ + id).innerHTML = content;
I starred this just because I wanted to create a mental image of what it was. Each value for “votes” will be displayed in its own div, so that when it is voted for we can just replace the inner HTML of that div with the new value.
We now need to originally display this data using PHP. This code will be embedded into the document somewhere. I warn you it’s not very pretty to look out (the echoed out result), however it is easy to modify it to fit your own site!
<?phpmysql_connect(“localhost”, “mysql_user”, “mysql_pass”); //Connect to the MySQL server with your host (probably localhost), your mysql username, and your mysql password
mysql_select_db(“db_name”); //Select your MySQL database by name
$query = mysql_query(“SELECT * FROM results ORDER BY count DESC”) or die(mysql_error()); //Query all possible options ordering by total votes
if( mysql_num_rows($query) ) //If there are any results to show…
{
while( $row = mysql_fetch_array($query) ) //Begin a loop to echo out each option
{
echo ‘<br /><strong>’. $row[‘option’]. ‘ <a href=”javascript:vote(’. $row[‘id’]. ‘)”>Vote!</a></strong><div id=”option’. $row[‘id’]. ‘”>’. $row[‘count’]. ‘</div>’; //Echo out each option, vote link, and total votes
}
}
else
{
echo “<p>Sorry, there are no options to vote for!</p>”; //Otherwise we echo out that message
}
?>
Now here is a SAMPLE page. You would most likely not want to have your page looking like this as it is quite boring. It is very easy though to take the pieces of code as examples and incorporate them into your own design. I’m just displaying this so that you can see the whole script in action.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=“http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=“Content-Type” content=“text/html; charset=iso-8859-1″ />
<title>Look! A Poll!</title>
<script language=“javascript” type=“text/javascript”>
function vote(id){
var xmlhttp=false; //Clear our fetching variable
try {
xmlhttp = new ActiveXObject(‘Msxml2.XMLHTTP’); //Try the first kind of active x object…
} catch (e) {
try {
xmlhttp = new
ActiveXObject(‘Microsoft.XMLHTTP’); //Try the second kind of active x object
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!=‘undefined’) {
xmlhttp = new XMLHttpRequest(); //If we were able to get a working active x object, start an XMLHttpRequest
}
var file = ‘vote.php?id=’; //This is the path to the file we just finished making
xmlhttp.open(‘GET’, file + id, true); //Open the file through GET, and add the id we want to retrieve as a GET variable
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) { //Check if it is ready to recieve data
var content = xmlhttp.responseText; //The content data which has been retrieved
if( content != ‘n’ ){ //If the response was not “n” (meaning it worked)
content = content.replace(‘y’, ”); //Get rid of the y infront of our result *
document.getElementById(‘option’ + id).innerHTML = content; //Set the inner HTML of the div with the old value in it to the new value **
}
}
}
xmlhttp.send(null) //Nullify the XMLHttpRequest
return;
}
</script>
</head>
<body>
<p>Question? <!– Replace with your actual question of course! –></p>
<?phpmysql_connect(“localhost”, “mysql_user”, “mysql_pass”); //Connect to the MySQL server with your host (probably localhost), your mysql username, and your mysql password
mysql_select_db(“db_name”); //Select your MySQL database by name
$query = mysql_query(“SELECT * FROM results ORDER BY count DESC”) or die(mysql_error()); //Query all possible options ordering by total votes
if( mysql_num_rows($query) ) //If there are any results to show…
{
while( $row = mysql_fetch_array($query) ) //Begin a loop to echo out each option
{
echo ‘<br /><strong>’. $row[‘option’]. ‘ <a href=”javascript:vote(’. $row[‘id’]. ‘)”>Vote!</a></strong><div id=”option’. $row[‘id’]. ‘”>’. $row[‘count’]. ‘</div>’; //Echo out each option, vote link, and total votes
}
}
else
{
echo “<p>Sorry, there are no options to vote for!</p>”; //Otherwise we echo out that message
}
?>
</body>
</html>
And there you have it! You now have all the skill to make your own displayable poll! This next part is optional, and it is just some PHP scripts that show you how you could add and delete options through your own little admin panel.
<?php//Name this file whatever you want (.php of course
)
mysql_connect(“localhost”, “mysql_user”, “mysql_password”); //Connect to the MySQL server with your host (probably localhost), your mysql username, and your mysql password
mysql_select_db(“db_name”); //Select your MySQL database by name
$del = intval($_GET[‘del’]); //Retrieve the integer value of del through GET
if( $del ) //If there is actually something in the del variable…
{
mysql_query(“DELETE FROM results WHERE id = ‘$del’”) or die(mysql_error()); //Delete the option with that id
echo “<p>Thank you, the option you chose to delete was deleted.</p>”; //Echo out that message <–
}
if( $_POST[‘addOption’] ) //If the form for a new option has been submitted…
{
$option = addslashes($_POST[‘addOption’]);
mysql_query(“INSERT INTO `results` (`option`) VALUES (’$option’)”) or die(mysql_error()); //Insert a new row for that option
echo “<p>Thank you, your option has been added!</p>”; //Echo out that message <–
}
$query = mysql_query(“SELECT * FROM results”) or die(mysql_error()); //Query all of the options
if( !mysql_num_rows($query) ) //If no rows are found…
{
echo “<p>There are no options currently in the database.</p>”; //Echo out that there are none to be found
}
else
{
while( $row = mysql_fetch_array($query) ) //Set up a loop for the query using $row as the fetching variable
{
echo “<p>”. $row[‘option’]. ” - <a href=\”?del=”. $row[‘id’]. “\”>delete</a></p>”; //Echo out each option with a delete link
}
}
echo “<form name=\”add\” method=\”post\” action=\”$PHP_SELF\”>
<p><input type=\”text\” name=\”addOption\” /><input type=\”submit\” name=\”addSubmit\” value=\”Submit\” /></p>
</form>”;
?>
Tips for modification
The main thing you would need to modify for this script would be the display because it is designed for utter simplicity. What you would want to change would be anything that is being displayed through echo. If you have a basic knowledge of HTML you should be able to change the various echoed out strings to fit your layout.
22 Jul
Posted by ProCOM
on July 22, 2007 – 12:48 am - 1,737 views
With the recent popularization of AJAX (Asynchronus Javascript And XML), it is now unnessecary to reload a page with the same basic layout, just to get new content. You can use AJAX to retrieve just the content without reloading the page, then change the value of a content area.
First of all, to use AJAX you must understand how it works. AJAX is JavaScript that can run through the “AJAX Engine” and by doing so, retrieve data from a remote page through HTTP, without having a page reload. It is similar to PHP’s file_get_contents(), however it can be done through JavaScript as a client-side script.
The first thing we need, is a php file that we will call with AJAX. It doesn’t have to be PHP, but since it is the most popular server-side language, that is what we’ll use. If you have decent knowledge of another language you would like to use instead, I’m sure you could translate the code. In this file, we will use a GET variable to determine the MySQL query we need to perform. We are using GET because it is accessible by AJAX. The great thing about it is that the file you are calling can be incredibly simple, and just be straight textual information. Here is an example:
<?php
//This file is text.php
mysql_connect(“localhost”, “username”, “password”); //Connect to the mysql server with your host (most likely localhost), username, and password
mysql_select_db(“db_name”); //Select your database by name
$page = $_GET[“page”]; //This is the variable we retrieve through GET to know which row of content to retrieve
$sql = “SELECT * FROM pages WHERE page = ‘$page’”; //This is the text of the query. We will select the content field from the table ‘pages’ where the page field has the same value as the one we want to retrieve
$query = mysql_query($sql) or die(mysql_error()); //Make the actual query
if( mysql_num_rows($query) == 1 ) //Check to see if we found 1 row with that page name
{
$r=mysql_fetch_assoc($query); //Set a mysql fetching variable for the query
echo $r[“content”]; //Echo out the content of the page we want
}
else
{
echo “Sorry, that page was not found.”; //Otherwise, echo out an error message saying the page was not found
}
?>
Now we have a file that will take in a page name through GET, query a row from our database with the same page name as that, then if that row exists, echo out the content of the page. We need a table in a database for this to work, however, so here is a very simple query to create a table with a field for page name and a field for content:
CREATE TABLE `pages` (
`page` VARCHAR( 255 ) NOT NULL ,
`content` TEXT NOT NULL
)
Next we need to create the AJAX function to call that file. I’ll start by posting the code then explain it:
function getPage(page){
var xmlhttp=false; //Clear our fetching variable
try {
xmlhttp = new ActiveXObject(‘Msxml2.XMLHTTP’); //Try the first kind of active x object…
} catch (e) {
try {
xmlhttp = new
ActiveXObject(‘Microsoft.XMLHTTP’); //Try the second kind of active x object
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!=‘undefined’) {
xmlhttp = new XMLHttpRequest(); //If we were able to get a working active x object, start an XMLHttpRequest
}
var file = ‘text.php?page=’; //This is the path to the file we just finished making *
xmlhttp.open(‘GET’, file + page, true); //Open the file through GET, and add the page we want to retrieve as a GET variable **
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) { //Check if it is ready to recieve data
var content = xmlhttp.responseText; //The content data which has been retrieved ***
if( content ){ //Make sure there is something in the content variable
document.getElementById(‘content’).innerHTML = content; //Change the inner content of your div to the newly retrieved content ****
}
}
}
xmlhttp.send(null) //Nullify the XMLHttpRequest
return;
}
You make have noticed that there are 4 lines of code that I placed asterisks by. I did that because I wanted to further explain them and tell you why they could be different for something else you might do with AJAX.
*
var file = ‘text.php?page=’; //This is the path to the file we just finished making *
The reason I starred this is becaused I didn’t have enough space to explain it in the comment. What you would have in this variable is your file (text.php in this instance) but with a blank form of your GET variable attached (page=) and of course you need the question mark (?) inbetween to separate the file extension from the GET variable. The reason we have a blank GET variable at the end is because in the next line we add the page title on to the end of it.
**
xmlhttp.open(‘GET’, file + page, true); //Open the file through GET, and add the page we want to retrieve as a GET variable **
I actually already explained why I starred this line. This first declares we’re retrieving data through GET, then we have our file variable (see *) followed by the page title. What this would look like if we weren’t using variables would be something like: text.php?page=home (pretending that home is the name of the page we want to retrieve).
***
var content = xmlhttp.responseText; //The content data which has been retrieved ***
I just starred this to make sure it was understood that we are merely putting the response text from the XMLHttpRequest into the variable content so it’s easier to work with. You don’t have to name it content, however if you change it make sure you change all of the other places where it is used also.
****
document.getElementById(‘content’).innerHTML = content; //Change the inner content of your div to the newly retrieved content ****
Currently what this line does is it changes the inner content of your div to the newly retrieved content. In this case we are using a div with the id ‘content’. If you have basic knowledge of JavaScript, you could do whatever you wanted with the content by now. For this tutorial I wanted to put the content into a div, but you could do with it what you like!
What I’m going to do now is put up an example html page (we’ll call that index.html) with the JavaScript AJAX functions embedded in it and two divs (one for content and another for a couple of example links).
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=“http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=“Content-Type” content=“text/html; charset=iso-8859-1″ />
<title>Our wonderful AJAX page!</title>
<script language=“javascript” type=“text/javascript”>
function getPage(page){
var xmlhttp=false; //Clear our fetching variable
try {
xmlhttp = new ActiveXObject(‘Msxml2.XMLHTTP’); //Try the first kind of active x object…
} catch (e) {
try {
xmlhttp = new
ActiveXObject(‘Microsoft.XMLHTTP’); //Try the second kind of active x object
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!=‘undefined’) {
xmlhttp = new XMLHttpRequest(); //If we were able to get a working active x object, start an XMLHttpRequest
}
var file = ‘text.php?page=’; //This is the path to the file we just finished making *
xmlhttp.open(‘GET’, file + page, true); //Open the file through GET, and add the page we want to retrieve as a GET variable **
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) { //Check if it is ready to recieve data
var content = xmlhttp.responseText; //The content data which has been retrieved ***
if( content ){ //Make sure there is something in the content variable
document.getElementById(‘content’).innerHTML = content; //Change the inner content of your div to the newly retrieved content ****
}
}
}
xmlhttp.send(null) //Nullify the XMLHttpRequest
return;
}
</script>
</head>
<body>
<div id=“links”>
<a href=“javascript:getPage(’home’)”>Home</a> <a href=“javascript:getPage(’page2′)”>Page 2</a>
</div>
<div id=“content”>
</div>
</body>
</html>
And there you have it, you’ve now got everything you need to make a simple page system using AJAX, PHP and MySQL. Just as a note, you’ll need to actually create rows in your table with page names home and page2 for this to work
Those are just examples though so you can use them as a model for other links.
The focus method is handy when error checking forms. All it does is put the cursor in the given element, which although simple, can be quite handy for the user. Using focus is really simple:
<script type=‘text/javascript’>
function error_check()
{
if(document.myform.myfield.value == ‘’)
{
alert(“Please fill in all fields!”);
document.myform.myfield.focus();
return;
}
else
{
//sucess, what to do. . .
}
}</script>
Useful and simple, a very good combination. Focus is a pretty simple function, but it adds to the user experience, which is always good.
Note: In order to use this tutorial, you need to have the prototype javascript library.
My earlier post on Prototype talked about two of the basic functions, now we’re going to use those functions along with the built-in AJAX functions to make a simple little application. Our application is simply for dummy purposes, but will tell us who has birthdays in certain months. In our script, we will first have to include the Prototype and script.aculo.us libraries; Prototype must be called first!
We will be using the Ajax.Request function which takes a two paramaters, the URL of the handler, and the options. Options specify which method we will be using, the data we send, and what to do when the script completes. All the JavaScript coded by us is a mere 5 lines!
We’re going to setup our table first, which is really simple, just run this query on your database:
CREATE TABLE `birthdays` (`name` varchar(255) NOT NULL DEFAULT ‘’, `age` int(3) NOT NULL DEFAULT ‘0?, `day` int(2) NOT NULL DEFAULT ‘0?, `month` int(2) NOT NULL DEFAULT ‘0?) ENGINE=InnoDB DEFAULT CHARSET=latin1
Next, we will code the AJAX handler script which receives a month number, then fetches all birthdays in that month:
mysql_connect(‘localhost’, ‘root’, ‘’);
mysql_select_db(‘tutorials’);
$query = mysql_query(“SELECT `name`, `age`, `day` FROM `birthdays` WHERE `month` = ‘{$_POST[’month’]}’”);
$out = “<ul>”;
if(mysql_num_rows($query) > 0)
{
while($r = mysql_fetch_row($query))
{
$out .= “<li>{$r[0]} turns {$r[1]} on the {$r[2]}</li>”;
}
}
else
{
echo “No birthdays in this month!”;
}
$out .= “</li>”;
echo $out;
?>
This is not complicated code, just a simple SELECT query and a while loop. Now, you may ask how we get the month number? That’s what Prototype sends us through post (you can use get, too). Whatever we echo, Prototype will get and store in the AJAX object as you will see shortly.
Our JavaScript contains one function! It starts and handles the request all at once.
function fetch_birthdays()
{
var month = $F(‘month’);
new Ajax.Request(‘ajax.php’, {method:‘post’, postBody:‘month=’ + month, onSuccess: function(t) { $(‘birthdays’).innerHTML = t.responseText; }});
}
We make use of our $F and $ functions; $F to get the current month from our select (which you’ll see later), and $ to update the div’s contents with the birthdays. Our AJAX request tells that the handler will be ajax.php, the method withh be post, and the data to send is month = whatever the month currently is. The onSuccess part may look weird to you. All we’re really doing is passing our AJAX object as a paramter (Prototype handles this), and then updating our div with the server’s response text, which will be an ordered list with birthdays!
The only part left is creating our form and update div, which is simple:
<h2>Birthdays</h2>
<p>Select a month from the drop down to see whose birthdays are in each month.</p>
<form name=‘months’>
<select id=‘month’>
<option value=‘1?>January</option>
<option value=‘2?>February</option>
<option value=‘3?>March</option>
<option value=‘4?>April</option>
<option value=‘5?>May</option>
<option value=‘6?>June</option>
<option value=‘7?>July</option>
<option value=‘8?>August</option>
<option value=‘9?>September</option>
<option value=‘10?>October</option>
<option value=‘11?>November</option>
<option value=‘12?>December</option>
</select>
<input type=‘button’ value=‘get birthdays’ onclick=“fetch_birthdays();” />
</form>
<div id=‘birthdays’></div>
Our button will call the fetch_birthday function which starts the AJAX request. . .
22 Jul
Posted by ProCOM
on July 22, 2007 – 12:38 am - 417 views
I recently found out about and downloaded a wonderful little package called script.aculo.us, for more information, check out my post on it. I’m going to assume that you have already downloaded script.aculo.us, which includes the Prototype JavaScript framework. The framework contains many functions, but we’re only going to cover two right now. These functions will be $ and $F (weird names, but you’ll find out why soon!)
The first function, $, will make your JavaScript development hundred’s of times faster. Honestly. Now, typing out document.getElementById(’id’) can get rather tiresome pretty quickly. Prototype’s $ function recgonizes this, it does the same thing as document.getElementById, but does it in one character! Here’s an example if you’re still a little confused:
var the_html = $(‘my_div’).innerHTML;
The next function is $F, it’s for forms. All you need to do is give one paramater, that is the input, select, radio button, etc name. $F will return the current value of that field! No more document.form_name.field_name.value, hoorah! Another example in case you’re still in the dark:
Enter your name: <input type=‘text’ id=‘my_name’ /> - <input type=‘button’ onclick=“alert(’Hi’ + $F(’my_name’) + ‘, I\’m Mike!);” value=’say hi!’ />
This is just the basics of Prototype, the rest of it is even cooler!
script.aculo.us is a JavaScript library containing easy to use scripts for drag and drop, visual effects, AJAX, autocompletion, element manipulation, and debug functions. The library requires Prototype (which is the AJAX, element manip. part of script.aculo.us), but it’s shipped with a current version.
The site provides easy to use documentation and examples that will get you started instantly. I’m no JavaScript expert, but I was able to look at the examples, and go from there. Right now, I’m working on a tutorial that uses script.aculo.us to do in place editing, AJAX interaction, etc. It’s the most fun I’ve ever had writing a tutorial, definitly check it out! ![]()
A common mistake made in JavaScript is the difference between names and IDs. In some browsers you are able to directly access an element by its ID such as:
document.id.(attribute)
However, that doesn’t work in all browsers and therefore should not be used. The correct way to access an element by its ID is with the function getElementById(), which is actually quite easy to remember if you think about it
. This would be the way to use it:
document.getElementById(‘id’).(attribute)
Generally when the name attribute is used it’s for forms, and thus requires the name of the form to be called as well. The structure for this is:
document.formName.elementName.(attribute)
It’s a pretty simple concept, however it’s often misused, so make sure you know what you’re trying to do before you do it!
JavaScript has a handy, and fun, little thing called document.title, all it does is change the title, but it’s handy in certain situations. One of these situations is when dealing with AJAX, I was fetching a post, but the title remained the same.
I quickly learned about document.title, and all my troubles were gone.
All it takes is:
document.title = document.titleform.newtitle.value;
That would work if I had a form named titleform with a field called newtitle. To best implement this, it should be stored in a function, let’s say change():
function change(title)
{
document.title = title;
}
This code will change the title to whatever we want. *evil* I want it to update every keystroke, so we’re going to use the method onkeyup:
<form>
New Title: <input type=‘text’ onkeyup=‘change(this.value);’ />
</form>
Yea, I know, it’s really that simple.
This is a special keyword, it means what you think, this! So it means this value, which is our new title. Heh, now, go off and entertain yourself with this. ![]()
Confirming with JavaScript is actually quite easy. You can just use a simple if/else statement with it and then have something happen in each situation.
What we’ll be using is the function confirm(). The confirm function is set as a variable initially then you can use the associated variable to check the outcome of the confirmation. On the user end they get a small alert window with your question asked in it and either an “OK” or “Cancel” option.
So, to begin we need to define our confirm pop-up. For this example we’ll ask the user if they want a cookie.
var wants_a_cookie = confirm(“Would you like a cookie?”);
That will put up the window, however there will be no consequence whether they press OK or Cancel. That’s where the if/else comes into play. The confirm() function when acknowledged will return either TRUE or FALSE. What we can do is just have a situation for each option. For this example I’ll just have an alert pop up telling them if they or if they don’t want a cookie.
if( wants_a_cookie ){
alert(“Hooray! You want a cookie!”);
}
else{
alert(“Oh no, you don’t want a cookie!”);
}
And that’s it! If you want the entire code to copy into your file it would look like this:
<script language=“JavaScript” type=“text/javascript”>
var wants_a_cookie = confirm(“Would you like a cookie?”);
if( wants_a_cookie ){
alert(“Hooray! You want a cookie!”);
}
else{
alert(“Oh no, you don’t want a cookie!”);
}
</script>