This blog has moved here: woorkup.com | FOLLOW ME ON TWITTER @woork
Monday, October 22, 2007

Insert record into database using Ajax and PHP

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:

  1. index.php (contains a simple form with an input text)
  2. ajax_framework.js (the javascript function to enable ajax functionalities)
  3. 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>


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();


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;
}
}


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!';
}
>


Save all, and try it in your localhost!

blog comments powered by Disqus
Adam said...

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.

Masiosare said...

Just 2 tips:

Search for unobtrusive javascript
Learn about sql inyection

Don't give a bad advice to your readers :)

Anonymous said...

Hi,
I am trying this on my localhost, but at the time of insertion, it shows this error.
Unknown column '' in 'field list'

Anonymous said...

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}')";

Anonymous said...

nice lesson , but i have a problem using it in Firefox . it appears just in loading and nothing insert .. can it be solved

Anonymous said...

can you give some example of insert record with a file ?

text+file i mean

mike said...

Thank you very much.

Anonymous said...

Thanx Antonio!

Cool tip that solved a big problem.

Cheers,
Constantinos
Thessaloniki, Greece

UNGAL NANBAN said...

I am also having problem in insertion in firefox can any one find the solution for me

john said...

Thank you so much :)

Rami said...

thank you very much ^___^

Anonymous said...

Nice and very understandable tutorial

Does it work with hidden inputs?

Thank you

Cristóbal said...

-Thanks for posting useful things.

gioxlit said...

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

Anonymous said...

nice , but the fields stay having the value posted , is there any solution to set fields empty again ?

  • 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