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;
	$("#div.data").each(function(){
		item = $(this).val();
		items.Category[item] = myval();
	});
	function myval() {
		// get data for the value part
		return data;
	}
	$.ajax({
		type: 'POST',
		cache: false,
		url: window.location.href,
		data: items,
		success: function(data){/* callback */}
	});

Using your own jQuery file with Yii

(and have them play nice)

A common issue and one that I knew there was a Yii solution for but didn’t see clearly documented is how to include your own jQuery file, particularly on a site that has mixed pages where Yii includes it’s own version on some pages and not on others — which can result in jQuery loading twice and causing problems that are not always immediately obvious as to the cause.

In any case, this should do the trick. If you don’t need jQuery on every page, you can leave off or wrap the registerScriptFile line in a conditional and Yii will use your jQuery file when it needs it.

$cs=Yii::app()->clientScript;
$cs->registerScriptFile(Yii::app()->getBaseUrl() . '/js/libs/jquery.min.js', CClientScript::POS_HEAD);
$cs->scriptMap=array(
    'jquery.js'=>Yii::app()->getBaseUrl() . '/js/libs/jquery.min.js',
);