Friday, September 21, 2012

submit a form as serialized JSON

This code was handed to me today by Will Hendrix. I have not tried it out yet. It should allow for a form's contents to be serialized and sent as JSON upon a form submission. I assume it requires a reference to the jQuery library, although there is a joke about the word assume.

function SubmitForm(formName, success, failure) {
   
   
// Select the form, by it's ID
   var theForm = $("#" + formName);
   
   
// Check to see if form exists
   if (theForm.length == 0)
      return;
   
   
// Create the JSON to represent the action parameters
   var params = theForm.serializeObject();
   
   var action = theForm.attr("action");
// action will contain controller/action
   if (action.length == 0)
      return;
   
   $.ajax({
      url: action,
      type: "POST",
      cache: false,
      data: JSON.stringify(params),
      dataType: "html",
      contentType: "application/json; charset=utf-8",
      error: failure,
      success: success
   });
}

 
 

I will also require this...

<script type="text/javascript" src="http://www.JSON.org/json2.js"></script>

 
 

It will also require this plugin too...

$.fn.serializeObject = function () { var o = {}; var a = this.serializeArray(); $.each(a, function () { if (o[this.name] !== undefined) { if (!o[this.name].push) { o[this.name] = [o[this.name]]; } o[this.name].push(this.value || ''); } else { o[this.name] = this.value || ''; } }); return o; };

 
 

It was good working with Will Hendrix at HDRI, he is a very sharp senior developer. This is one of the photos he created in holding the aperture open on a camera while spinning a glowing yo-yo in the dark of the night:

Share photos on twitter with Twitpic

No comments:

Post a Comment