Ajax Updates |
- Reddit-style Voting With PHP, MySQL And jQuery
- Create a Realistic Hover Effect With jQuery
- PrettyPrint for JavaScript
- Get Slick Effects with MooTools Kwicks
Reddit-style Voting With PHP, MySQL And jQuery Posted: 02 Oct 2009 11:22 AM PDT Let’s Get Started I created a table called entries where there are 5 columns: * id — The unique id associated with each entry In order to test the application, we insert some dummy data. Fetch The Data We create a config.php file that holds all our database credentials. < ?php $hostname = "localhost"; $db_username = "your_username"; $db_password = "your_password"; $link = mysql_connect($hostname, $db_username, $db_password) or die("Cannot connect to the database"); mysql_select_db("your_database") or die("Cannot select the database"); ?> What we did is just connect to the database. Do replace your_username, your_password and your_database with your own values. < ?php include("config.php"); ?> <html> <head> <title>Entries</title> <script type='text/javascript' src='jquery1.3.pack.js'></script> </head> <body> < ?php /** Display the results from the database **/ $q = "SELECT * FROM entries"; $r = mysql_query($q); if(mysql_num_rows($r)>0): //table is non-empty while($row = mysql_fetch_assoc($r)): $effective_vote = $row['votes_up'] - $row['votes_down']; //this is the effective result of voting up and voting down ?> <div class='entry'> <span class='link'> <a href='<?php echo $row['link']; ?>'> < ?php echo $row['title']; ?> </a> </span> <span class='votes_count' id='votes_count<?php echo $row['id']; ?>'>< ?php echo $effective_vote." votes"; ?></span> <span class='vote_buttons' id='vote_buttons<?php echo $row['id']; ?>'> <a href='javascript:;' class='vote_up' id='<?php echo $row['id']; ?>'></a> <a href='javascript:;' class='vote_down' id='<?php echo $row['id']; ?>'></a> </span> </div> < ?php endwhile; endif; ?> </body> </html> First, we include the config.php file to get access to database. Then we query the database to show all the entries found in the table. Next, we loop through the resultset and create a div for each entry. Notice the id attribute of both votes_count and vote_buttons classes. Since they id attributes are suffixed with the < ?php echo $row['id']; ?> , it would be different for different entries which would be helpful to identify each entry. Also the id of both vote_up and vote_down links are unique for each entry. body { background: #e8e6de; } a { outline:none; } .entry { width: 710px; background: #ffffff; padding:8px; border:1px solid #bbbbbb; margin:5px auto; -moz-border-radius:8px; } span.link a { font-size:150%; color: #000000; text-decoration:none; } a.vote_up, a.vote_down { display:inline-block; background-repeat:none; background-position:center; height:16px; width:16px; margin-left:4px; text-indent:-900%; } a.vote_up { background:url("images/thumb_up.png"); } a.vote_down { background:url("images/thumb_down.png"); } Notice, we added text-indent:-900% to vote_up and vote_down classes. This is a nice trick to hide the text and coming clear to search engines. Now if you view the index.php in browser it would show you the entries and you should land with something like this: Make Ajax Calls But first we create votes.php file and in it, write two functions that would be useful. include("config.php"); //config.php is added to get access to database connection function getAllVotes($id) { /** Returns an array whose first element is votes_up and the second one is votes_down **/ $votes = array(); $q = "SELECT * FROM entries WHERE id = $id"; $r = mysql_query($q); if(mysql_num_rows($r)==1)//id found in the table { $row = mysql_fetch_assoc($r); $votes[0] = $row['votes_up']; $votes[1] = $row['votes_down']; } return $votes; } This function is pretty simple. It expects an integer as its parameter and selects all the data from the table matching the id. Then it returns an array whose first element is votes_up and the second one is votes_down. function getEffectiveVotes($id) { /** Returns an integer **/ $votes = getAllVotes($id); $effectiveVote = $votes[0] - $votes[1]; return $effectiveVote; } This function depends on the first one and calculates the difference between votes_up and votes_down. Now, we add the following code to votes.php file: $id = $_POST['id']; $action = $_POST['action']; //get the current votes $cur_votes = getAllVotes($id); //ok, now update the votes if($action=='vote_up') //voting up { $votes_up = $cur_votes[0]+1; $q = "UPDATE entries SET votes_up = $votes_up WHERE id = $id"; } elseif($action=='vote_down') //voting down { $votes_down = $cur_votes[1]+1; $q = "UPDATE entries SET votes_down = $votes_down WHERE id = $id"; } $r = mysql_query($q); if($r) //voting done { $effectiveVote = getEffectiveVotes($id); echo $effectiveVote." votes"; } elseif(!$r) //voting failed { echo "Failed!"; } First, we get the requested id and the action. Then the current votes of the id. Remember $cur_votes is an array whose first element is votes_up and the second one is votes_down. Next, then query is determined on the basis of the action requested. Then, we simply update the table and display the value. Mighty jQuery $(function(){ $("a.vote_up").click(function(){ //get the id the_id = $(this).attr('id'); // show the spinner $(this).parent().html("<img src='images/spinner.gif'/>"); //fadeout the vote-count $("span#votes_count"+the_id).fadeOut("fast"); //the main ajax request $.ajax({ type: "POST", data: "action=vote_up&id="+$(this).attr("id"), url: "votes.php", success: function(msg) { $("span#votes_count"+the_id).html(msg); //fadein the vote count $("span#votes_count"+the_id).fadeIn(); //remove the spinner $("span#vote_buttons"+the_id).remove(); } }); }); }); When ‘Vote up’ link is clicked, first we get the unique id of the link. Then we show a cool ajax loader in place of the links. Also we fade out the vote count. Next, we make an ajax call and when the response from the script is received, we display the response with a fade-in effect and remove the spinner. Similarly for vote down link we would have: $("a.vote_down").click(function(){ //get the id the_id = $(this).attr('id'); // show the spinner $(this).parent().html("<img src='images/spinner.gif'/>"); //the main ajax request $.ajax({ type: "POST", data: "action=vote_down&id="+$(this).attr("id"), url: "votes.php", success: function(msg) { $("span#votes_count"+the_id).fadeOut(); $("span#votes_count"+the_id).html(msg); $("span#votes_count"+the_id).fadeIn(); $("span#vote_buttons"+the_id).remove(); } }); }); All these javascript code goes inside a tags of course. That’s all! Related Listings:
| |||||
Create a Realistic Hover Effect With jQuery Posted: 02 Oct 2009 10:50 AM PDT For one of the projects I'm currently working on with rareview, we wanted to add a rising hover effect to a set of icon links. Using jquery's animate effect, I experimented with icons that have reflections and others with shadows. Here is a demo with two examples:
The HTML and CSS are both straightforward and have a structure and style common to many web navigations and menus (for the sake of post length, I'm not including HTML/CSS code examples here but you are free to snoop around in the demo or view the files in the download below).
In a nutshell, the JS appends the reflection/shadow to each then animates the position and opacity of these elements and the icon links on hover. I've added .stop() to eliminate any queue buildup from quickly mousing back and forth over the navigation.
// Begin jQuery $(document).ready(function() { /* =Reflection Nav -------------------------------------------------------------------------- */ // Append span to each LI to add reflection $("#nav-reflection li").append("<span> </span>"); // Animate buttons, move reflection and fade $("#nav-reflection a").hover(function() { $(this).stop().animate({ marginTop: "-10px" }, 200); $(this).parent().find("span").stop().animate({ marginTop: "18px", opacity: 0.25 }, 200); },function(){ $(this).stop().animate({ marginTop: "0px" }, 300); $(this).parent().find("span").stop().animate({ marginTop: "1px", opacity: 1 }, 300); }); /* =Shadow Nav -------------------------------------------------------------------------- */ // Append shadow image to each LI $("#nav-shadow li").append('<img class="shadow" src="images/icons-shadow.jpg" alt="" width="81" height="27" />'); // Animate buttons, shrink and fade shadow $("#nav-shadow li").hover(function() { var e = this; $(e).find("a").stop().animate({ marginTop: "-14px" }, 250, function() { $(e).find("a").animate({ marginTop: "-10px" }, 250); }); $(e).find("img.shadow").stop().animate({ width: "80%", height: "20px", marginLeft: "8px", opacity: 0.25 }, 250); },function(){ var e = this; $(e).find("a").stop().animate({ marginTop: "4px" }, 250, function() { $(e).find("a").animate({ marginTop: "0px" }, 250); }); $(e).find("img.shadow").stop().animate({ width: "100%", height: "27px", marginLeft: "0px", opacity: 1 }, 250); }); // End jQuery }); Please note, for the purposes of this quick demo, I did not bother including support for IE6. Related Listings:
| |||||
Posted: 02 Oct 2009 09:58 AM PDT Those of you following me on Github may have noticed a recently added project called "prettyPrint". "prettyPrint" is an in-browser JavaScript "variable dumper" similar to ColdFusions's cfdump. It enables you to print out an object of any type in table format for viewing during debugging sessions. In combination with Firebug, "prettyPrint" will make you the best-equipped JavaScript debugger on earth! (not guaranteed) Some of its key features: * Entirely independent. It requires NO StyleSheets or images. I've recorded a short screencast demonstrating a couple of prettyPrint's features: "prettyPrint" is entirely independent. As mentioned, it requires NO StyleSheets or images. All styles are applied directly (inline) and are customizable via the exposed config object (prettPrint.config.styles). Using it is simple enough: var table = prettyPrint( anyRandomThing, { /*optional options object */ } ); // Making the table viewable is down to you... // e.g. document.body.appendChild(table); Related Listings:
| |||||
Get Slick Effects with MooTools Kwicks Posted: 02 Oct 2009 09:25 AM PDT When it came time for my employer to redo their website, I made it my goal to really jazz up the site with MooTools. Nothing too fancy and nothing too bright, just some simple effects that show attention to detail and a little bit of fun. I then thought it was the time to use MooTools "kwicks" to give the website a little kick. Step 1: Create Images You'll need an image for kwick, obviously. Make them all the same width. Below are my images, all 285 pixels x 143 pixels. Black borders have been added to show you image dimensions. Step 2: The HTML Showing the HTML first will give you a good idea of how kwicks are structured. <div id="kwick"> <ul class="kwicks"> <li><a class="kwick john" href="http://en.wikipedia.org/wiki/John_lennon" title="John Lennon"><span>John Lennon</span></a></li> <li><a class="kwick paul" href="http://en.wikipedia.org/wiki/Paul_mccartney" title="Paul McCartney"><span>Paul McCartney</span></a></li> <li><a class="kwick george" href="http://en.wikipedia.org/wiki/George_harrison" title="George Harrison"><span>George Harrison</span></a></li> <li><a class="kwick ringo" href="http://en.wikipedia.org/wiki/Ringo_starr" title="Ringo Starr"><span>Ringo Starr</span></a></li> </ul> </div> Step 3: The CSS There's minimal CSS involved in this process so don't worry about stylesheet bloat. #kwick { width:590px; } #kwick .kwicks { height:143px; list-style-type:none; margin:0; padding:0; } #kwick li { float:left; } #kwick .kwick { display:block; cursor:pointer; overflow:hidden; height:143px; width:134px; } #kwick .kwick span { display:none; } #kwick .john { background:url(kwicks/john.gif) no-repeat; } #kwick .paul { background:url(kwicks/paul.gif) no-repeat; } #kwick .george { background:url(kwicks/george.gif) no-repeat; } #kwick .ringo { background:url(kwicks/ringo.gif) no-repeat; } You only need to edit two lines of code in this example: 9 and 10. Nine defines the "squeeze" width of each kwick: how slim do you want blurred kwicks? Line 10 defines the maximum width of a kwick, which you'll likely want to be the full width of your image. Related Listings:
|
You are subscribed to email updates from Ajax Updates To stop receiving these emails, you may unsubscribe now. | Email delivery powered by Google |
Google Inc., 20 West Kinzie, Chicago IL USA 60610 |
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.