CMS Instant Edit (2 of 3)

This is the second edition to our instant edit tutorial. Today I will be expanding our instant edit to work with Ajax to save and retrieve information from our server side language PHP and a MySQL database.

We left off with a our functions fully created to perform our instant edit via client site DOM scripting. Now we must add functions that will send and retrieve data from our database but doing so with out any page refreshing and at the right spots in our already performing instant edit script.

First lets talk a little about Ajax and what it is. Ajax is a form of performing server side functions through a client side request so we can now talk,send and retrieve information from our server. Before AJAX, client side requests and server side request were two different worlds that required a page to be sent off to another page that would the preform our server side actions and carry variables out and back to our original page.

With Ajax in our corner we can preform server side actions or requests through one single page and do so with client side requests resulting in the spawn of internet application developing. Ajax requires some routines that use JavaScript to preform our post and get methods to our server side request. I personally use the well put together Ajax library from dynamicdrive.com that can be downloaded here.

We will not go into what makes up these routines as there are many tutorials out on the net on how to build ajax get and post routines instead lets talk about how we can use these routines to our advantage. In our working document we have to link to our Ajax routines.js file you just downloaded by adding the following to your header tags.

<script type="text/javascript" src="routines.js" ></script>

This brings our required routines to our document so we may build with them to create our needs. Ok so this is a good time to think about what our need are going to be with our instant edit. We need to have a location in our database that stores and retrieves our instant edit data. Then when ever the page loads either it being a first visit or refresh we can pull this data from out database to begin edits. After a user has finished editing a paragraph we want to send the edits out to our server and into our database to save the edits permanently.

Let start by creating our function that saves our data to our database. Add the following save function to you instant edit script:

function saveDoc()
{
	function createpoststring()
	{

		var currentEdit = document.getElementById('pallet').innerHTML;
		var poststr = "currentEdit=" + encodeURI(currentEdit);
		return poststr;
	}
		createpoststring();
		var poststr = createpoststring(); //Get contents to post and create query string first
		ajaxpack.postAjaxRequest("save2database.php", poststr, createpoststring, "html");
}

This is our saveDoc() function that creates a poststring or rather a secure variable string over to our server side functions via HTTP request. With in this function we have a second function named “createpoststring()” and in this function we have two variables.

Our first variable is named “currentEdit” and it points to our div container “pallet” and grabs its innerHTML. Our second string is the “poststr” and its creates our HTTP string by first making up the variable name our server side function will receive “currentEdit=” and attaches our innerHTML as a secure encoded URI.

Last we return the posts our of the function upon it ever being performed.

After our “createpoststring()” function we must run it by calling to it by means of “createpoststring();” so we may gather our encoded string and begin to process it. Our last variable is named poststr and it takes our function “createpoststring” and equals its self to its returned encoded string.

The last line of code uses our AJAX routines “ajaxpack.postAjaxRequest(“”,,””,);” to being sending our encode string over to our server side function. When using our AJAX routines we must use a set of commands if you will, that first point to the location of our server side function or rather server side file “save2database.php” then use the “poststr” variable to attach our encoded string to our AJAX post request. We will then call to our createpoststring to verify that our encoded version is true and ready to process. The last command is prerequisite of “html” stating that we wish to only send html type of data.

Great lets move onto building our openDoc function.

function openDoc()
{
	ajaxpack.getAjaxRequest("openFromDatabase.php", "", processOpenFile, "html");
}

    //LOAD FILE FUNCTION
    function processOpenFile()
    {
        var myajax = ajaxpack.ajaxobj;
        var myfiletype = ajaxpack.filetype;
        if (myajax.readyState == 4)//if request of file completed
        {
            if (myajax.status == 200 || window.location.href.indexOf("http") == -1)
            {
                if (myfiletype == "html")
                {
                    document.getElementById("pallet").innerHTML = myajax.responseText;
                    setParagrahEvent();
                }
                else
                {
                    alert(myajax.responseXML);
                }
            }
        }

    }

Ok here we have two functions that I like to think of as one. The first function is openDoc and it uses getAjaxRequest routine to call to a server side function or rather file “openFromDatabase.php” to process via server side and send it back down to client side.

To process this information back to our client side we must call to the function that will process our server side data by calling to our “processOpenFile” function.

Our “processOpenFile()” function is also calling and using our AJAX routines to setup an object that will represent our returning data and process it through a 4 step readyState process. Once we have received our readyState to be equal to our 4 and final step we bring our processed data back down to client side via a HTTP request

Once our data has been properly requested and processed we run it through as simple condition that states if its anything else then “html” or rather text then respond with an error. If indeed our requested data is that of html and or text we can place the returned data where ever we wish.

Our goal with the “openDoc()” function is to retrieve date from our server on every open of this instant edit script in order to populate our edit area with the most updated paragraph edits. So in order to perform such a thing we want to call a loss request to our openDoc() by adding “openDoc();” to our script.

Here is our complete AJAX open and save functions

openDoc();

function saveDoc()
{
	function createpoststring()
Ultrasound is used for cialis cost low  guidance in order to tackle these concerns. As a remedy in digestive disorders Garlic stimulates peristaltic action and the secretion of the digestive enzymes inside the pancreas; accordingly, it leads to self-digestion, destruction of the cialis 40 mg http://www.donssite.com/OPTICALIILLUSIONS/index1.htm pancreatic tissue and inflammation. Would you love to be able to tell your friends and delivery overnight viagra like this your family that you were able to drive on their own. Men who endure androgenic alopecia (male pattern hair loss) are truly devastated and upset with their condition and are decisive of leimodoing anything just to halt their hair loss problem. donssite.com viagra online for sale 	{

		var currentEdit = document.getElementById('pallet').innerHTML;
		var poststr = "currentEdit=" + encodeURI(currentEdit);
		return poststr;
	}
		createpoststring();
		var poststr = createpoststring(); //Get contents to post and create query string first
		ajaxpack.postAjaxRequest("save2database.php", poststr, createpoststring, "html");
}

function openDoc()
{
	ajaxpack.getAjaxRequest("openFromDatabase.php", "", processOpenFile, "html");
}

//LOAD FILE FUNCTION
function processOpenFile()
{
    var myajax = ajaxpack.ajaxobj;
    var myfiletype = ajaxpack.filetype;
    if (myajax.readyState == 4)//if request of file completed
    {
        if (myajax.status == 200 || window.location.href.indexOf("http") == -1)
        {
            if (myfiletype == "html")
            {
                document.getElementById("pallet").innerHTML = myajax.responseText;
                setParagrahEvent();
            }
            else
            {
                alert(myajax.responseXML);
            }
        }
    }

}

Great now lets quickly think about how we want to begin to use these two functions. Well we know what we want to preform a openDoc on every loading of our instant edit but what about our saveDoc function. The saveDoc function would most likely want to be done after ever edit is complete even if its to open another edit from a previous edit.

Lets go back to our working instant edit and incorporate our “saveDoc()” function. In your removeTextarea() function we want to add our saveDoc() function so make it look like the follow:

function removeTextarea()
{
    var textarea = document.getElementById('currentEdit');
    var textareaInners = textarea.value;
    if(textareaInners == "")
    {
        alert('Sorry but in this demo you must have at least one character in your paragraph edit!');
        var makeNewP = document.createElement('p');
        var getParent = textarea.parentNode;
        var sibling = textarea.nextSibling;

        var textareaInners = "WE NEED TO HAVE SOME TEXT HERE TO EDIT AND SAVE TO OUR DATABASE!!";

        getParent.insertBefore(makeNewP,sibling);
        makeNewP.innerHTML = textareaInners;

        getParent.removeChild(textarea);
        setParagrahEvent();
        saveDoc();
    }
    else
    {
        var makeNewP = document.createElement('p');
        var getParent = textarea.parentNode;
        var sibling = textarea.nextSibling;

        getParent.insertBefore(makeNewP,sibling);
        makeNewP.innerHTML = textareaInners;

        getParent.removeChild(textarea);
        setParagrahEvent();
        saveDoc();
    }
}

Ok so remember that upon every completed edit either it be from one edit to another we always close up or “remove” our working textarea so what better place to have our saveDoc() function to capture all completed edits then after our working textarea has been removed.

So you may now have tried to run the additions to our instant edit script and may have noticed that nothing is being saved out or retried from our database. This is because we have not created our server side functions or files “save2database.php” and “openFromDatabase.php”. Is the wizard behind the curtains to our completed instant edit script and begins our journey into our last section for this tutorial:

CMS Instant Edit Part 3.

Devin R. Olsen

Devin R. Olsen

Located in Portland Oregon. I like to teach, share and dabble deep into the digital dark arts of web and game development.

More Posts

Follow Me:TwitterFacebookGoogle Plus