Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In php must get data from jquery [object Object]

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).

like image 625
user2360831 Avatar asked Nov 21 '25 02:11

user2360831


1 Answers

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);
like image 80
Dilip Hirapara Avatar answered Nov 22 '25 15:11

Dilip Hirapara