Saturday, 9 February 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).

No comments:

Post a Comment