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 CONNECTIONif (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!








Awesome tutorial… works like a charm. Thanks for making it so easy and clear to implement.
sound interesting.. will give it a try.. hopefully it will solved my current project..
thanxxxxs !! – neo