views:

966

answers:

4

I've just written the easiest script in the world, but still I can't get it to work, and it's mighty strange. Here's the deal, what I want to do is to use jQuery to catch some input field values and serialize them with jQuery's serialize(); I then send the serialized string to the server to unserialize it. Here's the output I get from the serializing in jQuery, this is what I send to the server.

field1=value1&field2=value2&field3=value3

And here's the function;

public function unserialize_input()
{
    $str = $this->input->post("user_values");
    $unserialized = unserialize($str);
    var_dump($unserialized);
}

as I said, if I go "echo $str;" I get "field1=value1&field2=value2&field3=value3", so the string should be unserializable. How ever, I always get the same error message and the var_dump($unserialized); always returns bool(false);

Here's the error message I get from CodeIgniter, the framework I'm using for PHP.

Severity: Notice
Message: unserialize() [<ahref='function.unserialize'>function.unserialize</a>]: Error at offset 0 of 41 bytes

bool(false)

I'm using MAMP and running this locally at the moment, I read something about magic_quotes_gpc being OFF could cause this locally, but it's enabled. Any idea what might be wrong would be helpful. Thanks.

A: 

this is going to be a bit vague because i don't know jQuery overly well, but could it be that jQuery serialize's strings even slightly different from PHP? If so then that would cause the error message that you see

Marc Towler
+4  A: 

PHP's serialize and unserialize is to destruct and construct PHP objects/arrays/values.

Jquery serialize serializes a form into a POST string which can be very handy to do ajax calls. A post string is not a valid serialized string in PHP and cannot be reconstructed to a PHP mixed value and thus it returns false.

Martijn Laarman
Ok, so that's the reason. Thank you. Do you have any suggestion on how I can handle the data in the PHP script? As you said, it's really handy to send the input values as a serialized string in jQuery with the ajax call. But is there anyway I can convert the serialized string back into a php array or some other data type that php can handle easily, for example to insert the data into a database.
if you've sent the data with ajax, it will be in $_GET or $_POST, depending on the method you used for ajax
seanmonstar
Or to stay in the technology stack that you chose you could do the ajax call with $.post with jQuery and send the data as JSON. CodeIgniter can can reconstruct JSON to a php object/array/value checkout the json helper: http://blog.jdbartlett.com/2007/09/codeigniter-servicesjson.html. You can think of JSON as a universal format for serialze() and unserialize in a way.
Martijn Laarman
+6  A: 

You're using the wrong PHP function. You should use parse_str instead.

 parse_str($str, $unserialized);
Greg
That solved my problem, thank you sir!
A: 

Works for me too! thanks a lot man

djalma