Database Import Config Php Transitional Dtd organization Web Developer Web Developers Gods Gift Federal Employees Tag Nuances Color Schemes Laserjet 4100 Variables Images Links Working With Clients Csv blog Mumbo Jumbo Div Echo Lotus Notes Section 508 developer Integrity Php Password Ektron AJAX Index Screen Resolutions Services Software Deans List View Source Php File Transition Software Applications Telecommunications Products Color Scheme Formatting Video And Multimedia Time Frame Portable Computers Php Echo Import Functionality Social Networking Php Database Membership Login Husker Football Email Settings 2.6. 2.62 Traveling World Wide Web Web Adminemail Dashboard Server Hostname Multimedia Products Seo Search Engine Optimization box model Blackberry Internet Explorer Css File App Lt Addressbook Mysql Fetch Array encryption Page Rank Insanity Content Management System Css Files tricks New Features steps W3c 2.1 Development Area 51 Hourly Rates Download Cms Content Array develop css Time Web Select Name Gsa Gsa Gov SEO 26b Strange Person Web App Telegraph Ideas PHP Tips Search Google Membership Database Import Web Development Cat Id Free Phpmyadmin Branding Lotus Free Download free templates Hourly Fee Email Account CMS PHP Address Book Marketing WordPress database Firefox Web Applications Bandwidth Usage Password Reset Borders mySQL Categories University Web Headaches Html Xmlns Divs Military Installation Doctype Page Password Google rss Variation Joomla Colors Database Functionality Mysql Num Rows Accurate Time Internet Explorer 7 Php Variables Php Mysql Dynamic Css tips Last Straw Asynchronous Javascript And Xml Web Design Reference Habit News Releases Longest Time System Administrator Term Relationships tools XML Information Technology Products Br Tip Nate Lot Design Transparent Image Sql Database Indexing Services Fellow Web SQL Login Php Sql Server Intranet Information Systems Honesty Capital Letters Mobile Platforms Templates Search Engine Optimization Div Id Export Server Username Work Log Microsoft Rant Full Time Html Tag Stylesheet Forefront includes Strategy Football Game Double Benefit redirect
Database Import Config Php Transitional Dtd organization Web Developer Web Developers Gods Gift Federal Employees Tag Nuances Color Schemes Laserjet 4100 Variables Images Links Working With Clients Csv blog Mumbo Jumbo Div Echo Lotus Notes Section 508 developer Integrity Php Password Ektron AJAX Index Screen Resolutions Services Software Deans List View Source Php File Transition Software Applications Telecommunications Products Color Scheme Formatting Video And Multimedia Time Frame Portable Computers Php Echo Import Functionality Social Networking Php Database Membership Login Husker Football Email Settings 2.6. 2.62 Traveling World Wide Web Web Adminemail Dashboard Server Hostname Multimedia Products Seo Search Engine Optimization box model Blackberry Internet Explorer Css File App Lt Addressbook Mysql Fetch Array encryption Page Rank Insanity Content Management System Css Files tricks New Features steps W3c 2.1 Development Area 51 Hourly Rates Download Cms Content Array develop css Time Web Select Name Gsa Gsa Gov SEO 26b Strange Person Web App Telegraph Ideas PHP Tips Search Google Membership Database Import Web Development Cat Id Free Phpmyadmin Branding Lotus Free Download free templates Hourly Fee Email Account CMS PHP Address Book Marketing WordPress database Firefox Web Applications Bandwidth Usage Password Reset Borders mySQL Categories University Web Headaches Html Xmlns Divs Military Installation Doctype Page Password Google rss Variation Joomla Colors Database Functionality Mysql Num Rows Accurate Time Internet Explorer 7 Php Variables Php Mysql Dynamic Css tips Last Straw Asynchronous Javascript And Xml Web Design Reference Habit News Releases Longest Time System Administrator Term Relationships tools XML Information Technology Products Br Tip Nate Lot Design Transparent Image Sql Database Indexing Services Fellow Web SQL Login Php Sql Server Intranet Information Systems Honesty Capital Letters Mobile Platforms Templates Search Engine Optimization Div Id Export Server Username Work Log Microsoft Rant Full Time Html Tag Stylesheet Forefront includes Strategy Football Game Double Benefit redirect

I was working on a project yesterday that I found it necessary to create an auto-save feature do to the lengthy amount of text that would be entered into a text area. This is a little more complicated, but here it goes!

create.php

<?php
include ‘../../config.php’; //THIS FILE STARTS YOUR DB CONNECTION

if (isset($_POST["submit"])) {
$content = $_POST["content"];
$SQLsavearticle = “PUT SQL INSERT QUERY HERE”
$results = mysql_query($SQLsavearticle);
$found = mysql_num_rows($results);

if ($found == 0) { //IF THIS article HAS NEVER BEEN SAVED BEFORE THEN CREATE A NEW ENTRY
$SQLcreatearticle= “PUT SQL INSERT QUERY HERE”;
$results = mysql_query($SQLcreatearticle);
$chapterid = mysql_insert_id();
}
else {
$SQLupdatechapter = “SQL UPDATE STATEMENT HERE”;
$results = mysql_query($SQLupdatechapter);
$chapterid = mysql_insert_id();
}
}
else {
$SQLsavearticle = “SQL SEARCH FOR EXISTING entry”;
$results = mysql_query($SQLsavearticle);
$found = mysql_num_rows($results);

if ($found == 0) { //IF THIS article HAS NEVER BEEN SAVED BEFORE THEN CREATE A NEW ENTRY
$SQLcreatearticle= “PUT SQL INSERT QUERY HERE”;
$results =mysql_query($SQLcreatearticle);
$chapterid = mysql_insert_id();
}

$formdata = “<form method=\”post\” action=\”create.php\”>
<label>Content</label><textarea name=\”content\” id=\”content\”></textarea><br />
<input type=\”submit\” name=\”submit\” />
</form>”;
//SEARCH FOR BOOK ID IF IT EXISTS CONTINUE
?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title>Create a new chapter</title>
<script type=”text/javascript” src=”ajax/savearticle.js”></script>
</head>
<body onload=’process()’>
<?php
echo $formdata;
}
?>
<div id=”divMessage” />
</body>
</html>

I took out my SQL inserts, selects and updates because depending on how you have set up your database and what you are updating will determine how your queries are made. The second file is the javascript file with the AJAX calls in it. Now remember, as usual on all my script I work on, I create a link to my configuration file, which can be referenced on this post, if needed.

savearticle.js

// stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject();
// retrieves the XMLHttpRequest object
function createXmlHttpRequestObject()
{
// will store the reference to the XMLHttpRequest object
var xmlHttp;
// if running Internet Explorer
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject(“Microsoft.XMLHTTP”);
}
catch (e)
{
xmlHttp = false;
}
}
// if running Mozilla or other browsers
else
{
try
{
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
xmlHttp = false;
}
}
// return the created object or display an error message
if (!xmlHttp)
alert(“Error creating the XMLHttpRequest object.”);
else
return xmlHttp;
}

// make asynchronous HTTP request using the XMLHttpRequest object
function process()
{
// proceed only if the xmlHttp object isn’t busy
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
{
// retrieve the name typed by the user on the form
name = encodeURIComponent(document.getElementById(“content”).value);

// execute the quickstart.php page from the server
xmlHttp.open(“GET”, “savearticle.php?content=” + name, true);
// define the method to handle server responses
xmlHttp.onreadystatechange = handleServerResponse;
// make the server request
xmlHttp.send(null);
}
else
// if the connection is busy, try again after one second
setTimeout(‘process()’, 1000);
}

// executed automatically when a message is received from the server
function handleServerResponse()
{
// move forward only if the transaction has completed
if (xmlHttp.readyState == 4)
{
// status of 200 indicates the transaction completed successfully
if (xmlHttp.status == 200)
{
// extract the XML retrieved from the server
xmlResponse = xmlHttp.responseXML;
// obtain the document element (the root element) of the XML structure
xmlDocumentElement = xmlResponse.documentElement;
// get the text message, which is in the first child of
// the the document element
helloMessage = xmlDocumentElement.firstChild.data;
// update the client display using the data received from the server
document.getElementById(“divMessage”).innerHTML =
‘<i>’ + helloMessage + ‘</i>’;
// restart sequence
setTimeout(‘process()’, 1000*60*3);
}
// a HTTP status different than 200 signals an error
else
{
alert(“There was a problem accessing the server: ” + xmlHttp.statusText);
}
}
}

I know that this post may seem extremely complicated, but it is only because you cannot see my SQL statements or how its connected, but you should hopefully get the general idea. The last file is the referenced file in the javascript file above. This file is a PHP file, but since it is interpreted server-side, it appears to the javascript to be an XML file. The reason for this is to give the ability to save the draft to the database.

savearticle.php

<?php
include ‘../../../config.php’;
// retrieve the variables
$draft = $_GET['content'];
$articleid = $_GET['chapterid'];
$date = date(“F j, Y, g:i:s a”);
// Create SQL query to store text
 //UPDATE AN EXISTING DRAFT
 $SQLsavedraft = “SQL UPDATE QUERY TO UPDATE YOUR DRAFT TABLE”;
 $results = mysql_query($SQLsavedraft);

// we’ll generate XML output
header(‘Content-Type: text/xml’);
// generate XML header
echo ‘<?xml version=”1.0″ encoding=”UTF-8″ standalone=”yes”?>’;
// create the <response> element
echo ‘<response>’;
echo “Draft Saved on $date”;
echo ‘</response>’;
?>

Ultimately this AJAX program is very straight forward and will simply provide a text-area that will save a draft every 3 minutes to the database. I hope someone out there finds this useful!

  1. Awesome tutorial… works like a charm. Thanks for making it so easy and clear to implement.

    kengi on April 25th, 2009 at 2:24 am
  2. sound interesting.. will give it a try.. hopefully it will solved my current project..
    thanxxxxs !! – neo

    Aznan on December 30th, 2009 at 9:51 pm
Would you like to login?