Send array values from PhP form to JavaScript

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.

Advertisements

About admin

Just another php developer trying to give something back to the community.
This entry was posted in Script and tagged , , , , . Bookmark the permalink.

2 Responses to Send array values from PhP form to JavaScript

  1. Iman says:

    thanks that was useful

  2. “It’s actually a great and useful piece of information. I’m satisfied that you shared this helpful info with us. Please keep us informed like this. Thank you for sharing.”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s