zmol
zmol

Reputation: 1881

Sending array from javascript to php not working correctly

I'm creating an array on the jquery side this way. The array is an array of arrays where each element is an array that looks like [jskey, jsvalue].

    var jsarray = [];
//  jsarray.push([jskey, jsvalue]);
    jsarray.push([1, 123]);
    jsarray.push([2, 98]);
    jsarray.push([3, 107]);
    jsarray.push([4, 34]);

I then add the array to an element of a form before it's submitted

$('#myform input[name=jsvalues]').val(jsarray);

On the php side, I'm expecting to receive an array of array, but all I get when I do a print_r() or var_dump() is a string that looks like this

string() "1,123,2,98,3,107,4,34" 

Upvotes: 1

Views: 357

Answers (3)

Pierre
Pierre

Reputation: 1343

David Dorward gave a really good solution. To clarify a little bit, when you assign a complex object (like an array) to the attribute of a HTML element (that's what jQuery does when you call val()), the object is converted into a string (by calling the toString method on the object).

An array has a toString method that does exactly what you are experiencing: a list of the values inside the array separated by commas:

[1, [2, 3]].toString(); // returns "1,2,3"

To transmit complex objets, you can use JSON (JavaScript Object Notation) which is native in JS:

$('#myform input[name=jsvalues]').val(JSON.stringify(jsarray));

On the server side, PHP 5 has a really fast JSON API:

$jsvalues = json_decode($_POST['jsvalues']);

Upvotes: 2

Dan Grossman
Dan Grossman

Reputation: 52372

You could convert that string back into an array of arrays, assuming they were all pairs:

$arr = explode(",", $_POST['jsvalues']);
$jsvalues = array();
for ($i = 0; $i < count($arr); $i += 2) {
    $jsvalues[] = array($arr[$i], $arr[$i + 1]);
}

Upvotes: 0

Quentin
Quentin

Reputation: 943165

Attribute values are strings. When you convert an array to a string, you get each element in that array converted to a string and separated by commas (unless you override the toString() method (hint: don't)).

I suggest converting the array to JSON and then assigning that to the form control. You can then parse the JSON in PHP.

http://json.org has links (at the bottom) to PHP and JS implementations of JSON serializers / deserializers.

Upvotes: 5

Related Questions