This article is the fourth in a continuing series of DIY tutorials, which aims to make things as simple as possible.
To be honest, I wasn't planning on writing this article, but it would seem that there are quite a few people that want to know - what does the server-side code for the Ajax article look like?
In the previous Ajax article I outlined how to make a simple voting script, and a simple 'shoutbox' using Ajax. If you didn't read that post, I recommend doing so now, before reading this one.
It's always a bit harder to post server-side code, because there are a lot of ways you can do a something, and many people think their way is the better than any other. So let me just say that while there may be other ways to do things, this way works just fine. Anyway, back to your regularly scheduled program.
In this session, you are going to learn how to work the backend (in this case, PHP) for Ajax requests.
Previous articles in this series
- [Easy as Pie] Ajax Requests
- [Easy as Pie] Unobtrusive JavaScript
- [Easy as Pie] Working With A Database
What is PHP?
PHP is a server-side language, which means the server translates the code before sending to back to you. I'm no good at drawing diagrams, so imagine two computer-looking boxes. One of the boxes (the client, that's your browser) sends a request over to the other box (which is the server) which runs the server-side code, which then replies to your orinigal request with whatever the result is. Pretty simple. Other examples of server-side languages are ASP Classic, ASP.NET, Ruby on Rails and Coldfusion. If you want to learn more about server-side languages, you can read about them on the Wikipedia page for 'Server-side Scripting'.
So to not confuse anyone, I will be using the same examples from the last Ajax article (the fact that the code is already written played no part in this decision. Really.)
Voting Script
Okay, so here's the voting script:
Click on either the cat or the dog to vote for them. You can vote multiple times, so have a blast. Continue reading when you've had your fill.
Fun stuff. I'm not going to show the Ajax part of this example here (as I already did so in the previous article) so first, here's the database query you will need to run to set up the database:
CREATE TABLE `clicks` (
`id` tinyint(4) NOT NULL auto_increment,
`clicks` mediumint(9) default 0,
PRIMARY KEY (`id`)
)
See [Easy as Pie] Working With A Database for more information on how databases work and help on setting up your first script using one.
Now create two rows by running:
INSERT INTO `clicks` (`id`,`clicks`) VALUES ( '1',0) INSERT INTO `clicks` (`id`,`clicks`) VALUES ( '2',0)
And here's the PHP code for CallMe.php:
<?php
$user="username";
$password="password";
$database="database";
$votes = mysql_connect('localhost',$user,$password);
@mysql_select_db($database) or die( "Unable to select database");
if($_REQUEST['link'] == "1") {
$query="SELECT clicks FROM clicks WHERE id = 1";
} elseif($_REQUEST['link'] == "2") {
$query="SELECT clicks FROM clicks WHERE id = 2";
} else {
$query="SELECT clicks from clicks";
$result = mysql_query($query);
$votes1 = mysql_result($result,0);
$votes2 = mysql_result($result,1);
}
if($_REQUEST['link'] != "") {
$result = mysql_query($query);
$clicks = mysql_result($result,0);
$newClicks = $clicks+1;
}
if($_REQUEST['link'] == "1") {
mysql_query("UPDATE clicks set clicks = " . $newClicks . " where id = 1");
} elseif($_REQUEST['link'] == "2") {
mysql_query("UPDATE clicks set clicks = " . $newClicks . " where id = 2");
}
mysql_close($votes);
if($_REQUEST['link'] == "1") {
echo("I have " . $newClicks . " votes");
} elseif($_REQUEST['link'] == "2") {
echo("I haz " . $newClicks);
} else {
?>
<a href="javascript:void(0)" onclick="fillElementId('/landfill/CallMe.php','link1','link=1')" id="link1">I have <?php echo($votes1); ?> votes</a>
<a href="javascript:void(0)" onclick="fillElementId('/landfill/CallMe.php','link2','link=2')" id="link2">I haz <?php echo($votes2); ?></a>
<?php
}
?>
Now I'll go through and explain each block of code:
$user="username";
$password="password";
$database="database";
$votes = mysql_connect('localhost',$user,$password);
@mysql_select_db($database) or die( "Unable to select database");
This creates a connection to the database server.
if($_REQUEST['link'] == "1") {
$query="SELECT clicks FROM clicks WHERE id = 1";
} elseif($_REQUEST['link'] == "2") {
$query="SELECT clicks FROM clicks WHERE id = 2";
}
The $_REQUEST['link'] is getting the value of link which was posted by the Ajax. This section defines which option the user voted for.
} else {
$query="SELECT clicks from clicks";
$result = mysql_query($query);
$votes1 = mysql_result($result,0);
$votes2 = mysql_result($result,1);
}
The else in this code means, "if the user didn't click on '1' or '2' then run this." Then it creates a query that selects the clicks from the clicks table. It also sets the values of the $votes1 and $votes2 variables to whatever is in first and second cell, respectively.
if($_REQUEST['link'] != "") {
$result = mysql_query($query);
$clicks = mysql_result($result,0);
$newClicks = $clicks+1;
}
The if in this block checks to see if there was a vote cast (!= means does not equal, so what it is asking is 'if link does not equal nothing') and if so, it will execute the code in the block.
The code sets the variable $result to whatever is returned from the MySQL query, then sets $clicks to the first returned cell, and finally sets $newClicks to the same number as $clicks, but adds 1.
if($_REQUEST['link'] == "1") {
mysql_query("UPDATE clicks set clicks = " . $newClicks . " where id = 1");
} elseif($_REQUEST['link'] == "2") {
mysql_query("UPDATE clicks set clicks = " . $newClicks . " where id = 2");
}
This block checks to see which option was voted for, and updates the database accordingly.
mysql_close($votes);
Because we dont need the database connection any longer, we can close it.
if($_REQUEST['link'] == "1") {
echo("I have " . $newClicks . " votes");
} elseif($_REQUEST['link'] == "2") {
echo("I haz " . $newClicks);
This outputs (via echo) the new number of clicks on the item the user clicked on.
} else {
?>
<a href="javascript:void(0)" onclick="fillElementId('/landfill/CallMe.php','link1','link=1')" id="link1">I have <?php echo($votes1); ?> votes</a>
<a href="javascript:void(0)" onclick="fillElementId('/landfill/CallMe.php','link2','link=2')" id="link2">I haz <?php echo($votes2); ?></a>
<?php
}
This is the action that takes place when there was no vote counted (meaning the user just ran the script without voting) - This happens on the inital page load, so we can just use a php include to call it.
That's it for the voting script, now on to the:
Shoutbox
This tiny little script allows visitors to chat with you and other visitors.
- dede said: tete
- fucker said: you suck
- hg said: dgdgdg
- not bad said: not bad
- xxx said: asdfasdfasdf
- xxx said: sexsex
- test said: test
- Doron said: Test
- test break said: breakkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
- dsfg said: safddddddffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffuuuuuuuuuuuuuuuuuuuuucccccccccccccccccccccckkkkkkkkkkkkkkkkkkkkk
Here's the sql statement you need to use to set up the database:
CREATE TABLE `shoutbox` ( `id` mediumint(9) NOT NULL auto_increment, `ip` INT UNSIGNED default NULL, `timestamp` datetime default NULL, `message` varchar(100) default 'No Comment...', `name` varchar(30) default 'Anonymous', PRIMARY KEY (`id`))
Here's the code for the FillElement.php:
<?php
$user="username";
$password="password";
$database="database";
$shoutbox = mysql_connect('localhost',$user,$password);
@mysql_select_db($database) or die("Unable to select database");
$say = $_REQUEST['say'];
$name = $_REQUEST['name'];
if($say != "") {
if($name == "") {
$name = "Anonymous Coward";
}
$date = date("Y-m-d H:i:s");
mysql_query("INSERT INTO shoutbox (ip,timestamp,message,name) VALUES(INET_ATON('$REMOTE_ADDR'),'$date','" . mysql_real_escape_string($say) . "','" . mysql_real_escape_string($name) . "')");
}
$query="SELECT message, name FROM shoutbox ORDER BY timestamp DESC LIMIT 10";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close($shoutbox);
echo("<ul>\n");
for ($i = 0; $i < $num; $i++) {
if(($i % 2) == 1) {
$alt = "";
} else {
$alt = " class=\"alt\"";
}
$say = mysql_result($result,$i,"message");
$name = mysql_result($result,$i,"name");
echo("<li$alt><strong>".htmlentities($name)."</strong> said: ".htmlentities($say)."</li>");
}
echo("</ul>");
?>
Here's what's going on:
$user="username";
$password="password";
$database="database";
$shoutbox = mysql_connect('localhost',$user,$password);
@mysql_select_db($database) or die("Unable to select database");
Again we are setting up the connection to the database.
$say = $_REQUEST['say']; $name = $_REQUEST['name'];
I am just defining the $say and $name variables for easy use later.
if($say != "") {
if($name == "") {
$name = "Anonymous Coward";
}
This makes sure that $say is set, then checks if $name is set. If no $name was specified, it defaults to 'Anonymous Coward'
$date = date("Y-m-d H:i:s");
mysql_query("INSERT INTO shoutbox (ip,timestamp,message,name) VALUES(INET_ATON('$REMOTE_ADDR'),'$date','" . mysql_real_escape_string($say) . "','" . mysql_real_escape_string($name) . "')");
This sets the $date variable to the current time. This is the format it outputs it in: 2008-10-10 15:14:27. It then inserts data into the database.
You may notice I am running a MySQL function called INET_ATON on the ip address($REMOTE_ADDR). This saves some space in the database, taking up only 4 bytes, but if I had been using a varchar(15) and storing the IP normally, it would take up 15 bytes for each entry. For a little application like this, it's probably not a big deal, but it certainly doesn't hurt.
And as always, don't forget to escape everything you get from a user before putting it in the database.
$query="SELECT message, name FROM shoutbox ORDER BY timestamp DESC LIMIT 10"; $result=mysql_query($query); $num=mysql_numrows($result);
The first line of this block is creating a query which selects both the message and the name from the shoutbox table, orders it by the timestamp field descending (meaning newest first) and limits the return to 10 rows. Then we store the return in a variable called $result, then count how many rows were returned, using mysql_numrows().
mysql_close($shoutbox);
You should always close the connection as soon as you are done needing it
echo("<ul>\n");
for ($i = 0; $i < $num; $i++) {
As you can see, it is writing a starting <ul>. The \n means 'new line', so it will start a new line before echoing the <li>'s. The next line is a loop. The for loop will simply loop through until the condition is no longer met -- in this case, as soon as $i becomes greater than $num.
if(($i % 2) == 1) {
$alt = "";
} else {
$alt = " class=\"alt\"";
}
This fun little bit of code may look a bit different to you. Some of you may be familiar with the 'mod' command. That is exactly what this is. The % is short-hand for mod. Mod simply gets the remainder of an equation. In this case, it gets the remainder of $i divided by 2. It checks to see if the remainder equals 1. This will be true for every odd number. As you can see from the code following the statment, it will set the variable $alt to have a class of 'alt' for all even values. This way, we can "zebra-stripe" or in other words, alternate colors.
$say = mysql_result($result,$i,"message");
$name = mysql_result($result,$i,"name");
echo("<li$alt><strong>".htmlentities($name)."</strong> said: ".htmlentities($say)."</li>");
Now we are setting the values of $say and $name to be what we get out of the database, then outputting the whole line. Again, you will notice that I am escaping the output with htmlentities().
echo("</ul>");
And finally, we close the unordered list, and end the PHP.
Download the code
Because I know that I learn far better from example, I have made this code available for download. Click the following links to download the PHP files in zip format.
That's all, folks
And another [Easy as Pie] article comes to fruiition. I would like to take a moment and thank everyone for dropping by, and I really hope that I have helped you with something that might have previously been very confusing. If I did help you, please leave a comment letting me know. As always, be sure to subscribe to my RSS Feed for notification of future articles.













