Archive

Archive for December, 2008

Save an HTML Form With AJAX

December 13th, 2008 4 comments

If you’re reading this then you already have some experience with that wonderful little aspect of javascript that allows you, the developer, to deliver content to your users without reloading an entire page in the browser. If you think that AJAX is just some Greek warrior (you literary nerd, you) first head here to start using what has already become damn near ubiquitous on the web. The rest, please read on.

So you already know how to send/receive data with javascript do you? Good. Let’s beef those javascript skills up even further then. The catch, as it were, to saving data from an HTML form, is in treating each type of HTML element differently. Or rather, to realize that they all behave differently and that you’re going to have to build your javascript to treat them differently to. In short, make it play nice-like with the other kiddies.

Plain vanilla text inputs are easy enough.

getValue = document.form.inputName.value;

or

getValue = document.getElementById('inputID').value;

But how do we handle checkboxes? What about the select element? First, let’s assume that we do only have plain text inputs in our form. Unlikely in the real world, but it will give us a base function, which makes use of the super awesome built in js function, getElementsByTagName. It should be noted that this always returns an array of HTML elements.

/*
form here is the HTML form object
An easy way to pass this from your page to the function:
<form name="formName" onsubmit="saveForm(this);">
*/
function saveForm(form)
{
  // key is the primary key in the db
  // this would most likely be a hidden input in your form
  // I use it as a base to start building the query string
  // we want to create something that looks like
  // ?key=keyValue&input1=value1&input2=value2
  var q = (form.key ? '?key='+form.key.value : '?key=');

  var els = form.getElementsByTagName('input');

  //parse input elements
  for(var i=0;i<els.length;i++)
  {
      // for those familiar with php, escape is similar to urlencode
      // we need our data safe to pass in a url
      q += '&' + els[i].name + '=' + escape(els[i].value);
  }
}

This core function forms the basis for the rest of the exercise. We just need to work on ‘playing nice’ with the other elements. For the checkbox:

for(var i=0;i<els.length;i++)
  {
    if(els[i].type=='checkbox')
    {
      // I usually give my checkboxes values of 1 or 0
      // so we just check if it is checked, and pass
      // the value accordingly
      q += '&' + els[i].name + '=' + //-->
        (els[i].checked==true ? els[i].value : '0');
    }
    else
    {
      q += '&' + els[i].name + '=' + escape(els[i].value);
    }
  }

And the select element. The important thing to note about the select element is that we really don’t care about its values at all. It doesn’t even have any! OK, so you can often get away with grabbing the value from it, but what we are really doing is getting the values from its children; the option elements:

var sels = form.getElementsByTagName('select');

for(var i=0;i<sels.length;i++)
  {
    q += '&' + sels[i].name + '='
    for (var j=0; j<sels[i].options.length; j++)
    {
      if (sels[i].options[j].selected)
      {
        q += escape(sels[i].options[j].value)+',';
      }
    }
  }

OK, so learning time is over. If you are in a hurry like most developers and just scrolled down to the finished product, here you go. The whole function is here, with textarea thrown in to boot, free of charge.

function saveForm(form)
{
  // key is the primary key in the db
  // this would most likely be a hidden input in your form
  var q = (form.key ? '?key='+form.key.value : '?key=');

  var els = form.getElementsByTagName('input');

  //parse input elements
  for(var i=0;i<els.length;i++)
  {
    if(els[i].type=='checkbox')
    {
      q += '&' + els[i].name + '=' + //-->
        (els[i].checked==true ? els[i].value : '0');
    }
    else
    {
      q += '&' + els[i].name + '=' + escape(els[i].value);
    }
  }

  //parse textarea elements
  var tels = form.getElementsByTagName('textarea');

  for(var i=0;i<tels.length;i++)
  {
    q += '&' + tels[i].name + '=' + escape(tels[i].value);
  }

  // parse select elements
  var sels = form.getElementsByTagName('select'); 

  for(var i=0;i<sels.length;i++)
  {
    q += '&' + sels[i].name + '='
    for (var j=0; j<sels[i].options.length; j++)
    {
      if (sels[i].options[j].selected)
      {
        q += escape(sels[i].options[j].value)+',';
      }
    }
  }

  // this would be a call to an ajax handline function,
  // passing the url of our php file to save the data as
  // an argument
  sndReq('common/saveFormData.php'+q);
}