-3

I have a Javascript array containing Javascript Objects:

var fruits = []; 

var fruit = new Object; 
fruit.name = apple; 
fruit.color = red; 

fruits.push(fruit);

How do I pass this using JQuery's post $.post so that all its contents are accessible through PHP's $_POST array?

How are the object properties accessed with PHP?

dr_rk
  • 4,395
  • 13
  • 48
  • 74
  • 1
    possible duplicate of [Passing JavaScript Array To PHP Through JQuery $.ajax](http://stackoverflow.com/questions/2013728/passing-javascript-array-to-php-through-jquery-ajax) – Jay Blanchard Jul 14 '15 at 12:31
  • It is not a duplicate as the above mentioned question does not demonstrate how arrays containing Javascript objects should be handled. Do they need to be serialised before passing them through POST? How are they accessed with PHP's `$_POST`? – dr_rk Jul 14 '15 at 12:35
  • An array containing JavaScript objects? – Jay Blanchard Jul 14 '15 at 12:44
  • Like the example above where `fruit ` is an object with properties – dr_rk Jul 14 '15 at 12:47
  • @JayBlanchard not really necessary to convert to json to send to php... can use default internal form encoding – charlietfl Jul 14 '15 at 13:10
  • True @charlietfl, and what you're saying is stated in the duplicate. – Jay Blanchard Jul 14 '15 at 13:15

1 Answers1

1

You will end up with object looking like:

var fruit ={
  name:'Apple',
  color: 'Red'
}

You can simply post that object to php

$.post('path/to/server', fruit, function(resp){
   // validate response and do something
});

Default contentType for $.ajax of which $.post is a shorthand method is application/x-www-form-urlencoded so it is exactly the same as sending a form.

jQuery internals will take care of encoding the data object passed as argument to $.ajax or $.post or other shorthand methods

In PHP

$fruitName = $_POST['name'];
$fruitColor = $_POST['color'];

If you wanted to send the whole array you could do:

$.post(url, {fruits: fruits});

Then in php:

 $fruitsArray = $_POST['fruits'];
 foreach($fruitsArray as $item){
    $name = $item['name'];
 }
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • Your answer helped a lot. I hope this question will not be closed as I could not find on Stackoverflow details of particularly how Javascript Objects passed are accessed with PHP. – dr_rk Jul 14 '15 at 13:17