Posts tagged with “prototype”

15 Sep

Prototype Observer Pattern for using JSON via AJAX

This bit of Javascript code observes the “billing_info_bill_state” select field for changes every ’1.0’ seconds. Once changed, it sends the parameters to “update_totals.php”. It receives a JSON array via the X-JSON header and automatically eval’s it into an object that we can use to update the page.

<br />
new Form.Element.Observer(&#8216;billing_info_bill_state&#8217;, 1.0, function updateTotals(e){
	new Ajax.Request(&#8216;update_totals.php&#8217;,{
	  parameters: {
	    method: &#8216;get&#8217;,
	    evalJSON: true,
	    state: e.value},
	  onSuccess: function(transport,json) {
		  $(&#8216;billing_sales_tax&#8217;).update(json.tax);
		  $(&#8216;billing_subtotal&#8217;).update(json.total);
		}
	});<br />
});<br />