0

I am making an AJAX request and I need to send a complete PHP object. This is my JS code:

new Ajax.Request("some url", 
    {
        method: 'post',
        parameters: {
                      string1:"whatever",
                      myobject: this is where I want to send a PHP object named $product
                    }

     ...
    });

Whats the best way? Maybe using serialization?

Thanks for your help :)!

7
  • json Commented Jan 24, 2013 at 12:03
  • 1
    It's not a great practice to send a complete PHP object. You could serialize it, but the object's implementation isn't going to be sent of course, and it feels kludgy and a bit unprofessional. Why not expect a normal, language-agnostic JSON object, and parse that in PHP Commented Jan 24, 2013 at 12:03
  • So ill convert the PHP object in a JSON object? Is that what you mean? Commented Jan 24, 2013 at 12:04
  • Yeah, you could do that - json_encode($object) should work fine (not 100% sure what happens to private and protected members though, I guess they wouldn't be included) Commented Jan 24, 2013 at 12:05
  • 1
    Agreed with @Pekka웃 -- not good practice. If you could inject a complete PHP object into your program, it would probably represent a significant opportunity for hackers, particularly if you're using PHP's serialised format and just running unserialize() on it. Use a regular JSON object, and populate your PHP product object from the JSON within the PHP program. Commented Jan 24, 2013 at 12:07

2 Answers 2

2

You can try using json_encode(), sending that through the request and json_decode on the other side

Sign up to request clarification or add additional context in comments.

1 Comment

I tried <?php echo json_encode($product)?> but the results is just {} ... so its empty. What could be wrong?
1

It is not a good idea to send a plain php object. Even when you do something like json encoding. The problem is that the receiving side might not know about the objects class definition.

Instead I suggest you add some export/import moethods to your class definition. You send the (serialized) result of the export method and import that (unserialized) on the receiving side. That way it is a) clear that you have a valid class on the receiving side and b) you have a place to handle missmatches. You are more flexible and safer.

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.