Sunday, November 05, 2006

Passing UI filters as json to cgi scripts

We have a search page that allows the users to define custom filters through UI. One way to pass filter information to server side script is through hidden fields. However if the number of filters increase then this scheme can be a headache. For n filters you would need N input fields. what if we have a filter object in our javascript code ? How about taking all the input from user, creating a filter javascript object and passing that object to the server side script ?
Sounds nice ? All the house keeping can then be moved to OO style javascript.

Filter UI can be defined inside a standard HTML form.
<form name="filterForm" id="filterForm" method="post" action="/cgi-bin/store.pl">
name

other blah blah ..........
</form>

when the Filter form is submitted, a createFilter javascript method is called. This is not OO style but I would suggest doing that.

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

<script>
filterObj = {};
function submitForm(){
var filterForm = document.getElementById('filterForm');
var name = filterForm.name.value ;
blah blah .....
filterObj.name = name ; filterObj.age = age ; filterObj.sex = sex ;
filterForm.payload.value = filterObj.toJSONString() ;
filterForm.submit(); }
</script>


I got json.js library from www.json.org . This makes javascript manipulation easier. so just go and grab a copy. one caveat , GET was not submitting the json string for me, it was submitting individual members of the json object . I am using apache 2.2.x. Now, on the server side. you just extract the json string from request parameter and convert the json string to perl object using cpan JSON module.

use JSON ;
my $json = new JSON ;
my $js = my $jsObj = $json->jsonToObj($cgi->param('payload'));
# print members of this object
print " \n $jsObj->{'name'} :: $jsObj->{'age'} :: $jsObj->{'sex'} \n" ;

thats it folks!
© Life of a third world developer
Maira Gall