Passing JavaScript Objects to PHP
If you do not have JSON support enabled in your PHP installation, or simply do not want to deal with JSON, you are in luck. Since PHP can automatically convert array-style form fields to native arrays, all you need to use is midori.convertToFields(). This method converts the data stored in any JavaScript object to hidden form fields for transparent server-side processing.
midori.convertToFields() takes three parameters:
- parentNode is the node the new fields will be inserted into. This can be any DOM element such as a div.
- prefix is a string that will be added to the beginning of the names of the new input fields.
- a is an object that contains name-value pairs. Nesting objects is possible, but there is no check for duplicate keys.
midori.convertToFields(someObject, 'cities',
{ 'San Francisco': 'CA', 'Seattle': 'WA', 'Chicago': 'IL' } );
After you run this, the contents of someObject will be:
<input value="CA" name="cities[San Francisco]" type="hidden"> <input value="WA" name="cities[Seattle]" type="hidden"> <input value="IL" name="cities[Chicago]" type="hidden">
Once the data is converted, you can simply include it in a form, or use midoriAjax to submit it in the background, and PHP will see it like this:
array ( 'San Francisco' => 'CA', 'Seattle' => 'WA', 'Chicago' => 'IL' )
