Monday, 22 October 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!

No comments:

Post a Comment