POST data to simulate HTML form checkbox submission

Not sure how often this may come up, or if this is the best approach but this worked for me in this particular situation and very well might be useful in the future.

The problem was that I wanted to re-use a form model in PHP to save data that was derived via multiple sources and hence had different formats. Since the server expected a specific format: $_POST['Category'] = Array([id]=>value) , I needed to do some reprocessing client-side and use jQuery to submit via POST. (Nothing here requires jQuery, mostly using for relative brevity.)

In this example we are fetching some Category IDs from DOM elements, which are then to be used as keys when the data is saved and the value derived via a function — but have all the data saved in the single $_POST['Category'] variable.

My solution was to use a nested object and let jQuery handle the form submit like:

	var items = {};
	var fn = 'Category';
	var val = {};
	items[fn] = val;
	var item;
		item = $(this).val();
		items.Category[item] = myval();
	function myval() {
		// get data for the value part
		return data;
		type: 'POST',
		cache: false,
		url: window.location.href,
		data: items,
		success: function(data){/* callback */}

Leave a Reply