Saturday, February 9, 2008

Using prototype.js to add record into database with ajax

Ajax for newbie: add a record into database table using prototype.js and PHP.

In the past weeks I wrote several posts about how to use ajax to add, modify, delete records from a database using ad hoc JavaScript functions. Now I want to use ajax requests using a very useful JavaScript framework called prototype.js.


This tutorial explains how to use prototype.js framework to enable a simple ajax request which add a new record (an user name) into a database table using PHP like server side language.

Download this tutorial (include prototype.js)


Step 1: include prototype.js
Download prototype.js and create a new page (index.php). Add this line of code in the <head> tag onf index.php to include prototype framework:

<script type="text/javascript" src="prototype.js"></script>


Step 2: HTML code for index.php
index.php is a simple page with a form like this:

<input type="text" name="user_name" id="user_name" />
<input type="submit" name="button" id="button" value="Insert" onclick="javascript:insertName()"/>


...where the input button calls a javascript function insertName() in onClick attribute (see Step 4 for more info about insertName()...).

Step 3: insert.php
Create a new page (insert.php). This page contains a simple query to save the new record into a database table (USER):

<?php
if(isset($_POST['user_name'])){
/* Connection to Database */
include('config.php');
/* Remove HTML tag to prevent query injection */
$name = strip_tags($_POST['user_name']);

$sql = 'INSERT INTO USER (name) VALUES(
"'.$name.'")';
mysql_query($sql);
echo $name;
} else { echo '0'; }
?>


Step 4: Javascript function to enable Ajax Request
This code enable ajax request with prototype. Add this lines of code below the code in step 2:

&l;script type="text/javascript">
function insertName(){
new Ajax.Request('insert.php', {
parameters: $('user_name').serialize(true),
});
}
</script>


We pass to index.php the value we want to save using this simple code:

$('user_name').serialize(true)

...if you have familiarity with javascript, this is equal to declare this code:

document.getElementById('user_name');


... where in both cases "user_name" is input field ID we want to save into database. We pass this value to insert.php like a POST variable (see step 3).

Friday, February 8, 2008

Drag and drop to order list elements with Scriptaculous

Drag and drop feature is a popular effect in modern website interfaces and a simple way to implement it is using Scriptaculous.

This tutorial explains how to use Scriptaculous to implement an HTML list with drag and drop feature to reorder list elements.


Download this tutorial

Step 1: Add scriptaculous framework
To enable drag and drop effect you have to download Scriptaculous framework here and add a link to prototype.js and scriptaculous.js in the <head> tag of your page:

<script src="scriptaculous/lib/prototype.js" type="text/javascript"></script>
<script src="scriptaculous/src/scriptaculous.js" type="text/javascript"></script>


Step 2: HTML Code
Add a <ul>list with ID "myList" and some <li> elements with a progressive ID like in the following example:

<ul id="myList" class="listClass">
<li id="item_1">Adobe</li>
<li id="item_2">Apple</li>
<li id="item_3">Microsoft</li>
<li id="item_4">Macromedia</li>
<li id="item_5">Symantec</li>
<li id="item_6">Mozilla Foundation</li>
<li id="item_7">Skype</li>
</ul>
<!-- Display a string with the new order after drag and drop here -->
<p id=
"listNewOrder">&lt/p>

Add this javascript code below the previous code:

<script type="text/javascript" language="javascript" charset="utf-8">
Sortable.create('myList',{ghosting:false, constraint:true, hoverclass:'over',
onChange:function(element){
// Total elements in the list (in this case 7 <li> element)
var totElement = 7;
var newOrder = Sortable.serialize(element.parentNode);
for(i=1; i<=totElement; i++){
newOrder = newOrder.replace("myList[]=","");
newOrder = newOrder.replace("&",",");
}
// display the string with the new order in the <Pgt; with id listNewOrder
$('listNewOrder').innerHTML = 'New Order: ' + newOrder;
}
});
</script>

newOrder is a string variable which returns the new order of all elements of "myList" for example:

1,2,4,3,5,6,7

... where list element 4 has moved before list element 3. The new order is:

li element 1 --> position 1
li element 2 --> position 2
li element 3 --> position 4 (changed from position 3 to position 4)
li element 4 --> position 3 (changed from position 4 to position 3)
li element 5 --> position 5
li element 6 --> position 6
li element 7 --> position 7

If you use PHP or another server side language like ASP or Coldfusion you can save the new list order assigning the value of newOrder to an hidden <input> HTML element in this way:

$('newOrderInput').value = newOrder;


... and adding an hidden input field with id newOrderInput in your HTML code after <ul> list with ID "myList":

<input type="hidden" id="newOrderInput" value="">

In this way every time you drag and drop a list item the value will be updated with the text string with the new order. Then you can use this string (for example "1,2,4,3,5,6,7") and PHP to save the new order into a database table.

Download this tutorial


Related Content
Effect appear (fade-in) using Scriptaculous
Toggle effect using Scriptaculous
Horizontal animated menu using Mootools
Mootools animated sidebar menu

Thursday, February 7, 2008

Effect appear (fade-in) using Scriptaculous

Scriptaculous Fade effect is one of my favorite effects of this framework and in this post I want to use it to implement a Digg-line sign-in bar.

My friend Ivan asked to me how to implement the same Digg-like fade-in effect which you can see when you click on the Login link on the Digg topbar. This is very simple using Scriptaculous and toggle effect with only few lines of HTML code.


Download this tutorial

Step 1: Download Scriptaculous Framework
Before to start, you have to download scriptaculous framework here and add a link to prototype.js and scriptaculous.js in the <head> tag of your page:

<script src="scriptaculous/lib/prototype.js" type="text/javascript"></script>
<script src="scriptaculous/src/scriptaculous.js" type="text/javascript"></script>


Step 2: HTML code
HTML code is very simple

<div id="login" style="display:none;">
Email <input name="email" type="text" /> Password <input name="password" type="text" /></div>
<a href="#" onclick="Effect.toggle('login','appear'); return false;">Login</a>

Effect.toggle() function takes as input two parameters: layer ID (in this case "login") and type of effect (in this case "appear" to simulate fade-in effect).

Download this tutorial

Wednesday, February 6, 2008

Search with autosuggest feature (Coldfusion)

Are you a Coldfusion developer? This tutorial help you to implement autosuggest feature for your website using Ajax.

Some days ago I wrote a post about this topic using PHP like server-side language and some readers asked to me how to implement the same ajax search with auto-suggest feature using Coldfusion.


Download this tutorial

How it works
The package contains:

- index.cfm (search form)
- search.cfm (Coldfusion code to execute query)
- ajax_framework.js (javascript functions to enable ajax feature)

When an user type a string in the input field with id "search-q" (in index.cfm) the function autosuggest() searches the current string into a database table...

<input name="search-q" id="search-q" type="text" onkeyup="javascript:autosuggest()"/>
<div id="results"></div>

... and the script shows search results into the <div> layer with id "result".

All files are fully customizable and ready to use in your coldfusion project. Remeber to change SQL code and datasource name in search.cfm using your correct datasource name.

Download this tutorial

Monday, February 4, 2008

My experience switching from a PC to a Mac

More then a year ago I was looking for a small notebook to substitute my old HP Pavilion notebook and, after some afterthoughts, I decided to switch from a PC to a Mac so I bought a MacBook (white) in an Apple Store in Rome.

This is my experience switching from Windows-based system to a Mac.



First Impression (vote: 8)
My parents bought me my first PC on 1992 and sice that moment I used all Windows versions, from 3.0 to Vista. So when I turned on my new MacBook, I admit it, the first impression has been not too enthusiastic. Yes... beautiful interface, fast response but honestly not so immediate for an "new-ex" Windows user.
Two hours after, I was completely addicted from the simplicity and extraordinary usability of Mac OS X Tiger (and now Leopard)!

Spotlight instant search (vote: 10+)
I 've never used search feature in Windows XP and, I think, I am not the only one. Be honest: it's an unserviceable functionality. An user can't spend more then ten minutes to find something on your PC! If I wanted to find easily some documents, the only way was to maintain organized my documents folder or use Google Desktop or Windows Desktop Search to have the "illusion" of a suitable search function on my Windows XP system. I have to say Microsoft has done big steps improving search feature in Windows Vista but search results are still not so accurate especially if you are searching for some text into your documents.
The situation is totally different in a Mac. With Spotlight you find exactly what you are searching for (applications, documents, text into a document, contacts, e-mails...) and search results are accurate and almost instant.

Using Microsoft Office 2004 and OpenOffice (vote: 4)
I daily use Microsoft Office 2003 / 2007 (on Windows XP/Vista) in my work, mainly to manage and design complex Excel files or integrate them with Access data. I believe, without doubt, it represents the state of the art if compared to other similar alternatives available on Windows. I can't say the same for Microsoft Office 2004 for Mac which is a very bad conversion of the office suite available on Windows. Working with Excel is frustrating and Word crash frequently when you add or modify tables. So I downloaded and tried OpenOffice but the impression hasn't been good and I decided to remove it. Now, I use Pages instead of Microsoft Word and Google Spreadsheets or Editgrid to manage (not for my job...) Excel files, waiting for the new Office Mac Version (2008)...

Using Apple Pages (vote: 9)
I like Pages. It's more then a powerful word processor. It is a "fusion" between Microsfot Word and Publisher with a simple and clear interface and also includes several useful features (you don't find in Microsoft Word...), such as executing basic operations between table's cells like if they was cells of an Excel spreadsheet.

Using Dreamweaver (vote: 8)
I didn't find big differences using Dreamweaver switching from Windows to Mac. Perhaps Mac version it's a little slower then Windows version but it mantains the same distinctiveness which do Dreamweaver the best software available to design and programming web sites in any language.

Forgot "essential" Windows software (vote: 10+)
Using Windows, I spent much time on download.com web site looking for new software to improve system security and performance (Ad-Aware, Norton updates, AVG antivirus, Spybot, Spyware doctor, Avast, Zone Alarm, Registry optimizer, defrag utilities, Diskeeper... the list is very long...). Using a Mac I forget antivirus software and all other "essential" Windows software to improve system performance.

iTunes (vote: 10+)
I've never liked iTunes on Windows XP. It is slow and crash frequently. So when I find iTunes icon on OSX dock bar I started to use it with some hesitation mainly because I didn't have found a good alternative like Media Player 11. But after some days I changed totally idea. iTunes for Mac is not the same software I used with Windows. Nothing to say: extraordinary. The best software I never seen and used to manage music, videos and podcast.

Mail and Safari (vote: 9+)
The best web experience I never done. Nothing to add!

Conclusion
Ok... then: "Mac yes or not?".
I think if you are a Windows user and you need to use mainly Excel and Access (with complex interactions between them and VBS macros) or other Windows-only-based software, switching to a Mac couldn't be a good idea. But if you are a web designer, a musician, a simple home user or you don't need strictly Widnows-based software, think to switch to a Mac. In any case, I suggest you to go to an Apple Store and take a look in person to the Apple product you want to buy in order to do a more conscious choice!

Sunday, February 3, 2008

XTorrent: torrent manager for mac

XTorrent is the best torrent manager / file sharing sofwtare for mac. Easy to use and with a simple interface.

If you are a Mac user and you are searching for a good .torrent software, I suggest you to take a look at XTorrent. I think it's the best .torrent manager for mac: fast, simple and with a nice interface iTunes-like.


You can download the full program here from the official site (only 3.8 Mb).

Friday, February 1, 2008

Search with autosuggest feature

Are you an Ajax newbie and are you looking for a simple way to implement autosuggest feature for your PHP site?

This tutorial explains how to implement a simple PHP ajax search with autosuggest feature using some lines of PHP and Javascript code. The result is like this:


How it works
The package contains:

- index.php (search form)
- config.php (MySQL connection's parameters. Change them!)
- search.php (PHP code to execute query)
- ajax_framework.js (javascript functions to enable ajax feature)

When an user type a string in the input field with id "search-q" the function autosuggest() searches the current string into a database table...

<input name="search-q" id="search-q" type="text" onkeyup="javascript:autosuggest()"/>
<div id="results"></div>

... and the script shows search results into the <div> with id "result".

All files are fully customizable. Remeber to change connection's parameter in config.php and SQL code for $getRecord_sql query in search.php. I used a generic query in search.php... change the code in bold changing table name (INVENTORY) and table field (TAG):

$getRecord_sql = 'SELECT * FROM INVENTORY WHERE TAG LIKE "'.$searchq.'%"';


Download this tutorial