AAA Главная
Примеры PHP Примеры JavaScript Примеры Ajax Примеры CSS,HTML

Использование prototype.js для добавления информации в базу данных с использованием AJAX.

Оригинал статьи здесь Prototype 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.

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):

 /* Connection to Database */
 /* 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'; }
<script type="text/javascript">
function insertName(){
new Ajax.Request('insert.php', {
parameters: $('user_name').serialize(true),

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),

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


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


... 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).


© Copyright 2008- by KDG

Rambler's Top100