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']);
mysql_query('INSERT INTO USER (name) VALUES("'.$name.'")');
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).