0

I created a jQuery array of objects:

my_family = [
person {
 name = “nick”,
 age = 41,
 role = “dad”
},
person {
 name = “john”,
 age = 4,
 role = “son”
},
person {
 name = “sarah”,
 age = 31,
 role = “mom”
},
]

I am trying to post this to the same page via post as a php array, which I have done successfully :

$.post("http://www.samepage.com", {my_family: my_family}); 

I then want to use this data, but when I try to add it to a variable or manipulate it in any way the page is not responding. when I use the following code, I can see it in my firebug as printed into the html, but I can not add it to variables or anything, how come? this is what I use to see it in html:

print_r ($_POST['my_family']);

furthermore it doesnt print to the page with the name "my_family" but just "Array". My main goal is to loop though the array and store each "age" value into a new array. is what Im doing possible via the post method?

2
  • I updated print_r ($_POST['my_family']);, mistake when trying to simplify the question for this post Commented Dec 9, 2015 at 2:25
  • are those “ ” curly quotes really part of your code? if so, that will break your code. Use regular quotes "var". Commented Dec 9, 2015 at 3:01

2 Answers 2

1

If you are POSTing some more complex data, you could try JSON.stringify that data, send it, and then decode it in PHP.

In JavaScript:

$.post("http://www.samepage.com", {my_family: JSON.stringify(my_family)});

In PHP:

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

// And if you're storing 'age' values into a new array
$age_values = array();
foreach($my_family as $person) {
    array_push($age_values, $person['age']);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, I've edited the PHP code because of some of my misunderstand of json_decode.
I think im having a problem with the first line of php, maybe my array is not compatible with the php array? here is what my array looks like after I post it with JSON.stringify: [{\"final_user_id\":\"1\",\"final_name_id\":\"1\",\"final_nametype\":\"spanish\",\"final_price \":\"33\",\"final_return\":\"1.8\"}]
1

Here it appears that you are trying to read data as a POST which is not a form-posted, $_POST is a just a wrapper for data which is either for

  • application/x-www-form-urlencoded (content type for simple form-posts) OR

  • multipart/form-data-encoded (for file uploads)

here basically you may want to read the JSON as raw input to php. // in your php file..

$data = json_decode(file_get_contents('php://input'));
print_r ( $data);

Comments

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.