This lesson will explains how to insert a record into a database table and show a message after insertion. In this example we will add a web site (URL and site name) into a table.
How does it works?
In the site root we have these files:
- index.php (contains a simple form with an input text)
- ajax_framework.js (the javascript function to enable ajax functionalities)
- insert.php (the PHP code to save the record into a database table)
Take a mind that index.php and ajax_framework.js are indipendent from the script language (PHP, ASP, Coldfusion...). For example index.php can be adopted also if you are using another script language changed only the extension (ex. from .php to .cfm if you use Coldfusion) without change the code.
Step 1: index.php
This is the code for index.php: a simple form that calls (in the action attribute) a javascript function, insertRecord(), in ajax_framework.js.
<!-- Include AJAX Framework -->
<script src="ajax/ajax_framework.js" language="javascript"></script>
<!-- Show Message for AJAX response -->
<div id="insert_response"></div>
<!-- Form: the action="javascript:insert()"calls the javascript function "insert" into ajax_framework.js -->
<form action="javascript:insert()" method="post">
<input name="site_url" type="text" id="site_url" value=""/>
<input name="site_name" type="text" id="site_name" value=""/>
<input type="submit" name="Submit" value="Insert"/>
</form>
<script src="ajax/ajax_framework.js" language="javascript"></script>
<!-- Show Message for AJAX response -->
<div id="insert_response"></div>
<!-- Form: the action="javascript:insert()"calls the javascript function "insert" into ajax_framework.js -->
<form action="javascript:insert()" method="post">
<input name="site_url" type="text" id="site_url" value=""/>
<input name="site_name" type="text" id="site_name" value=""/>
<input type="submit" name="Submit" value="Insert"/>
</form>
Step 2: the javascript function insert() in ajax_framework.js
In this lesson we have see how enable the XMLHTTPRequest. In ajax_framework.js file we have added this code:
/* ---------------------------- */
/* XMLHTTPRequest Enable */
/* ---------------------------- */
function createObject() {
var request_type;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}else{
request_type = new XMLHttpRequest();
}
return request_type;
}
var http = createObject();
/* XMLHTTPRequest Enable */
/* ---------------------------- */
function createObject() {
var request_type;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}else{
request_type = new XMLHttpRequest();
}
return request_type;
}
var http = createObject();
Now, in the same javascript file, we will add other lines of code for the function insert():
/* -------------------------- */
/* INSERT */
/* -------------------------- */
/* Required: var nocache is a random number to add to request. This value solve an Internet Explorer cache issue */
var nocache = 0;
function insert() {
// Optional: Show a waiting message in the layer with ID login_response
document.getElementById('insert_response').innerHTML = "Just a second..."
// Required: verify that all fileds is not empty. Use encodeURI() to solve some issues about character encoding.
var site_url= encodeURI(document.getElementById('site_url').value);
var site_name = encodeURI(document.getElementById('site_name').value);
// Set te random number to add to URL request
nocache = Math.random();
// Pass the login variables like URL variable
http.open('get', 'insert.php?site_url='+site_url+'&site_name=' +site_name+'&nocache = '+nocache);
http.onreadystatechange = insertReply;
http.send(null);
}
function insertReply() {
if(http.readyState == 4){
var response = http.responseText;
// else if login is ok show a message: "Site added+ site URL".
document.getElementById('insert_response').innerHTML = 'Site added:'+response;
}
}
/* INSERT */
/* -------------------------- */
/* Required: var nocache is a random number to add to request. This value solve an Internet Explorer cache issue */
var nocache = 0;
function insert() {
// Optional: Show a waiting message in the layer with ID login_response
document.getElementById('insert_response').innerHTML = "Just a second..."
// Required: verify that all fileds is not empty. Use encodeURI() to solve some issues about character encoding.
var site_url= encodeURI(document.getElementById('site_url').value);
var site_name = encodeURI(document.getElementById('site_name').value);
// Set te random number to add to URL request
nocache = Math.random();
// Pass the login variables like URL variable
http.open('get', 'insert.php?site_url='+site_url+'&site_name=' +site_name+'&nocache = '+nocache);
http.onreadystatechange = insertReply;
http.send(null);
}
function insertReply() {
if(http.readyState == 4){
var response = http.responseText;
// else if login is ok show a message: "Site added+ site URL".
document.getElementById('insert_response').innerHTML = 'Site added:'+response;
}
}
Step 3: insert.php
This is the insert.php page code:
<!-- Include Database connections info. -->
<?php include('config.php'); ?>
<!-- Verify if user exists for login -->
<?php
if(isset($_GET['site_url']) && isset($_GET['site_name'])){
$url= $_GET['site_url'];
$sitename= $_GET['site_name'];
$insertSite_sql = 'INSERT INTO SITE (site_url, site_name) VALUES('. $url. ',' . $sitename. ')';
$insertSite= mysql_query($insertSite_sql) or die(mysql_error());
<!-- If is set URL variables and insert is ok, show the site name -->
echo $sitename;
} else {
echo 'Error! Please fill all fileds!';
}
>
<?php include('config.php'); ?>
<!-- Verify if user exists for login -->
<?php
if(isset($_GET['site_url']) && isset($_GET['site_name'])){
$url= $_GET['site_url'];
$sitename= $_GET['site_name'];
$insertSite_sql = 'INSERT INTO SITE (site_url, site_name) VALUES('. $url. ',' . $sitename. ')';
$insertSite= mysql_query($insertSite_sql) or die(mysql_error());
<!-- If is set URL variables and insert is ok, show the site name -->
echo $sitename;
} else {
echo 'Error! Please fill all fileds!';
}
>
Save all, and try it in your localhost!

nice lesson, thanks for posting, i was looking around trying to find a solution to something i'm trying to build and this worked perfectly. i'm trying to create a page where visitors can leave a comment and i wanted it to be posted into the db and then display on the page without the page reloading. with a few minor tweaks i got this to work with my own site, thanks again.
Just 2 tips:
Search for unobtrusive javascript
Learn about sql inyection
Don't give a bad advice to your readers :)
Hi,
I am trying this on my localhost, but at the time of insertion, it shows this error.
Unknown column '' in 'field list'
I solve that problem with changing syntax in MySQL INSERT INTO statement on line 21 file insert.php
Before: $insertSite_sql = 'INSERT INTO SITE (site_url, site_name) VALUES('. $url. ',' . $sitename. ')';
After: $insertSite_sql = "INSERT INTO SITE (site_url, site_name) VALUES('{$url}' , '{$sitename}')";
nice lesson , but i have a problem using it in Firefox . it appears just in loading and nothing insert .. can it be solved
can you give some example of insert record with a file ?
text+file i mean
Thank you very much.
Thanx Antonio!
Cool tip that solved a big problem.
Cheers,
Constantinos
Thessaloniki, Greece
I am also having problem in insertion in firefox can any one find the solution for me
Thank you so much :)
thank you very much ^___^
Nice and very understandable tutorial
Does it work with hidden inputs?
Thank you
-Thanks for posting useful things.
any chance using mutiple forms in a single page?
i tried it out with no succes.
it just keeps inserting data from th first form
nice , but the fields stay having the value posted , is there any solution to set fields empty again ?