Slavenko Miljic
Slavenko Miljic

Reputation: 3856

Pass multiple javascript arrays to PHP page

I was trying to find an answer for this question for a while but no luck.

The problem is this. On one PHP page i have multiple javascript arrays (lets say 2). One of those arrays is an array that represents pieces of a shirt and the other array contains color of each piece.

  $pieces[0] = 'base';
  $pieces[1] = 'sleeves';
  $pieces[2] = 'pocket';

  $colors[0] = 'white';
  $colors[1] = 'red';
  $colors[2] = 'black';

On top of all that i have a form with where user can enter some data.

Now my question is, how can I pass those two arrays and form data to a PHP page?

Thanks for all your help.

/******
EDIT

******/

Well in case that someone has the same problem the solution is to serialize the arrays, insert them in a hidden field on a form and deserialize it on a PHP page

http://code.activestate.com/recipes/414334-pass-javascript-arrays-to-php/

Upvotes: 0

Views: 935

Answers (2)

Treffynnon
Treffynnon

Reputation: 21553

I am not sure if I get your question as you appear to have listed a PHP array there and not a Javascript one.

Passing as one array from JS

var pieces = [
    "base",
    "sleeves",
    "pocket"
];
var colors = [
    "white",
    "red",
    "black"
];
var send_array = {
    "colors": colors,
    "pieces": pieces
};
$.post('/my/url.php', send_array); //using jQuery for ajax request

Extracting json array in PHP

$send_array = json_decode($json, true);  

Passing as one array from PHP to JS

$pieces[0] = 'base';
$pieces[1] = 'sleeves';
$pieces[2] = 'pocket';

$colors[0] = 'white';
$colors[1] = 'red';
$colors[2] = 'black';

$send_array = array(
    'colors' => $colors,
    'pieces' => $pieces,
);
$json = json_encode($send_array);  

Upvotes: 1

DhruvPathak
DhruvPathak

Reputation: 43235

You can create a json of those two arrays and pass it to PHP. In PHP you can use json_decode() to get all the data.

eg:

http://codepad.org/r683RvsO

<?php

/* this json is received from javascript using ajax*/

$receivedJson =
'{
  "pieces" : ["base","sleeves","pocket"],
  "colors": ["white","red","black"]
}' ;

$infoArr = json_decode($receivedJson,true);

var_dump($receivedJson);

?>

Upvotes: 3

Related Questions