0

Okay i have some data that is entered by form and some that is generated by the page Here is my js file that gets and pushes the data to the php file

$(document).ready(
    function() {    
    $("#message_sender").submit(function(event){

        event.preventDefault();

        var sender_data = {
            avatar: document.getElementById("user_avatar_hidden").textContent,
            username: document.getElementById("user_username_hidden").textContent,
            message: $("#message_sender").serialize()
        };

        alert(sender_data.message);

        $.ajax({
             url: 'Js_returns/message_sent.php',
             type: 'post',
             data: {"data" : JSON.stringify(sender_data)},
             success: function(data) {
                $("#conversation_table").append(data);
             }
        });
    });
});

Now, im accesing the avatar and username normaly but i cant access the message part the way i want.

$var= json_decode($_POST["data"]);
    echo $var -> avatar;

So if i didnt convert the data into an js object i could easily do $_POST['message_title']; I have tried $var -> message -> message_title; (which i know makes no sense but what the heck) and it didnt work

PS the form im pushing with serialize consists of message_title and text_editor_area

3
  • When you json_decode it, it will become an associative array. You can't treat it as object. Try echo $var['avatar']; Commented Jul 31, 2015 at 21:06
  • Thats not the issue here... When i used json_decode it converted it into an object as said on the php.net site <?php $json = '{"foo-bar": 12345}'; $obj = json_decode($json); print $obj->{'foo-bar'}; // 12345 ?> I need a way to access the message object Commented Jul 31, 2015 at 21:10
  • Ok, if according to the manual shouldn't it be $var->{'avatar'}; rather than $var -> avatar; Commented Jul 31, 2015 at 21:24

1 Answer 1

1

PHP does NOT recursively decode a data structure. You sent over data=sometext structure, where sometext happens to be a JSON-endoded structure. When you decode that JSON, php has absolutely NO clue that message is a further serialized()'d data structure. YOU have to handle that yourself:

$var = json_decode($_POST['data']);
$unserialized_data = parse_str($var['message']);
Sign up to request clarification or add additional context in comments.

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.