Computing Magazine

Send Array Values from PhP Form to JavaScript

Posted on the 12 April 2013 by Akahgy

Description:

Having a PhP form, we need to manipulate in JavaScript an object that depends on the form input.

Solution:

The best way to do it is to use an encoded JSON object or an AJAX call. The AJAX call is pretty straight forward, but the use of a JSON object is recommended due to it’s ease of use and limited calls to the script.

In the case we have a form with checkboxes we need to send a whole object, or array, we first encode the JSON in PHP with json_encode() , send it as string in the checkbox value and in the javaScript function we only need to decode it , or evaluate it with eval() .

In PhP:

<?php
$arrayObject = array(‘id’ => $objectId, ‘name’ => $objectName, ‘price’ => $objectPrice, ‘description’ => $objectDescription);
?>
<span><input name=’object’ type=’checkbox’ value=’<?=json_encode($arrayObject)?>’></span>

Then, in JavaScript, for each checked checkboxes:

var decodedArray = eval(‘(‘+checkedItems[i].value+’)');
var id = decodedArray.id;
var name= decodedArray.name;
var price= decodedArray.price;
var description= decodedArray.description;

Of course in JavaScript you have to define how to get the checked checkboxes, or use ExtJS or other framework.


Back to Featured Articles on Logo Paperblog

Magazine