3

With jquery create array. With ajax ($.post) send the array and additional data to php. In php see [object Object]. And can not get data from [object Object].

Tried the below code:

var data_to_send = []; // actually here is is input fields .serializeArray()

var cars = ["Sa,coma,ab", "Vol,coma,vo", "B,coma,MW"];

data_to_send.push( 
{name: 'draft', value: 'some_value'}, 
{name: 'cars_init', value: {name: 'cars', value: cars}} 
);

$.post( filename.php, data_to_send, function(data_process_invoices) {
$('#show_result').html(data_process_invoices).css('color', 'black');
});

In php with echo '<pre>', print_r($_POST, true), '</pre><br/>'; get like this

Array
(
    [draft] => some_value
    [cars_init] => [object Object]
)

Tried to get something from [cars_init].

$array = get_object_vars( $_POST['cars_init'] );

Result is [object Object].

Tried $array = json_decode(($array), true); and foreach( $_POST['cars_init'] as $val ) { echo '<pre>', print_r( $val, true), '</pre><br/>'; }. As result see nothing. And also get php errors get_object_vars() expects parameter 1 to be object, string given and Invalid argument supplied for foreach(). As i understand for php [cars_init] is string... so question seems, how to convert it to array.

Instead of [object Object] just want to get array like this

 (
 [0] => Sa,coma,ab
 [1] => Vol,coma,vo
 [2] => B,coma,MW
 )

If i change jquery to $.post( filename.php, {data_to_send}, function(data_process_invoices) { i get some php array (with $_POST). But in such case get additional dimension and i need to use foreach to change (wasting of resources).

1 Answer 1

6
arrayOne = [{name:'a',value:1}, {name:'b',value:2}]
var arrayTwo = [{name:'foo',value:'blah'},{name:'arrayOne',value:arrayOne}];

Since you have a complex data structure, you should probably use JSON to encode your data:

data: {data: JSON.stringify(arrayTwo)},

and on the server you simply decode it with

$data = json_decode($_POST['data'], true);

$data will have the exact same structure as arrayTwo.

But in case you want to actually have parameters with names foo and arrayOne, then you only need to serialize the the value of arrayOne:

data:  [
  {name:'foo',value:'blah'},
  {name:'arrayOne',value: JSON.stringify(arrayOne)}
],

and in PHP:

$arrayOne = json_decode($_POST['arrayOne'], true);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, all works. Just needed to use JSON.stringify. I spend (wasted) ~ 5 hours "experimenting". Need to remember for future

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.