This blog has moved here: woorkup.com | FOLLOW ME ON TWITTER @woork
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).

blog comments powered by Disqus
Wayne Smallman said...

Antonio, thanks for the tutorial. I'm almost certain to be using this shortly.

Speak soon!

tom said...

try it with rails+prototype to discover how much simpler it could be

Kent Brewster said...

Strip_tags isn't nearly enough. I'm just sayin'.

David said...

Short, accurate, easy: Brilliant!
Thank you.

bloggerpaul said...

Great tutorial.

One question - there is no feedback that a record has been succesfully added. That is to say, there is no feedback after the record is added to say 'the record has been added'

Any chance of outlining how that might work?

Antonio said...

@bloggerpaul: I'll add the code for the response in the next days. Thanks for your suggest.

Anonymous said...

Thanks Superb

rasmit said...

Will this code work for jsp+prototype.js+windowsOS. Kindly update.

Jim said...

I've used the tutorial exactly as it is, but I'm getting a javascript error for line 11, char 1, error: Object expected, code: 0.

Any ideas? This is in IE. FF just doesn't work at all. :(

Janckos said...

gracias.

Rich McCue said...

Thank-you very much for this tutorial. It's the best thing I found on the topic this afternoon. I do have one question if anyone out there knows the answer. I can't seem to be able to get the script to work with more than one form field. Any easy way to make it work with multiple form fields?

Thanks again!

Anonymous said...

Thanks! I would also like to pass more parameters to this function. I have a JS var called getVars which contains, name=myname&age=25&sex=m

Is is best to pass getVars to the function:
function insertName(getVars)

Then use each value in the parameters?:

Ajax.Request('insert.php', {
parameters: $('name').serialize(true), $('age').serialize(true),$('sex').serialize(true),
});
}

Any help greatly appreciated.
Thanks again.

Arjun Kulkarni said...

In case if some one want to pass more than one parameter to insert.php using ajax you can do the following way

function insertName(){
var fname = $F('first_name');
var lname = $F('last_name');
var url = 'insert.php?' //if dosent work try giving the compelete path
var pars = 'first_name=' + fname + '&last_name=' + lname;
new Ajax.Request(url, {method: 'get',parameters: pars});
}

Arjun Kulkarni said...

In order to display a successfully inserted message on index.php all you need to do is just add an AJAX event "onCompelete" to the previous code after adding it looks something like this function
insertName(){
var fname = $F('first_name'); //Input text field name
var lname = $F('last_name'); //Input text field name
var url = 'insert.php?' //if dosent work try giving the complete path
var pars = 'first_name=' + fname + '&last_name=' + lname; //you can pass as many parameters as you want in the similar manner
new Ajax.Request(url, {method: 'get',parameters: pars,onComplete: showResponse}); }
function showResponse(originalRequest) { $('result').innerHTML = originalRequest.responseText; }

and below the submit button (or anywhere you wish to) place
<span id="result" style="color:#009900"> </span>
and in insert.php at the last line just before the end of flower bracket place this line (you can edit the text as you want) echo "
Inserted into Database Successfully";

Thank you Antonio for providing us a base for exploration in the form of such a wonderful code

  • Twitter Follow woork on Twitter
  • RSS Feed Subscribe to stay up to date
  • Podcast Coming soon...
  • 0 delicious lovers save
Share your links. Do you want to suggest any interesting link about web design or tech news? Submit your link.
Submit a News