jQuery to PHP - serialized strings

I'm currently AJAX'ing a login form.

var data = $(this).serialize();

This is the data I'm sending, I get this with PHP using Codeigniter like so:

$ajax = $this->input->post('data');

This returns username=john&password=doe as you'd expect.

How do I turn that into an array? I've tried doing unserialize() and I get null.

Answers


I believe you can use PHP's parse_str() function: http://php.net/manual/en/function.parse-str.php

<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first;  // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz

parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

?>

Using your code it would be:

parse_str($this->input->post('data'), $ajax);
echo $ajax['username'] . "/" . $ajax['password'];

Short answer is with parse_str;

parse_str($ajax, $array);
$array === array('username'=>'john', 'password'=>'doe');

However, the way you send your ajax data is a bit odd. Why are you serializing to a formencoded string and sending that string as a value to the 'data' parameter? Why don't you just send it directly? Then you could use $this->input->post('username') === 'john' without the extra level of deserializing.

For example, do this:

$.post(url, $(form).serialize());

instead of this (which you seem to be doing:

$.post(url, {data:$(form).serialize()});

Need Your Help

Which database has the best support for replication

mysql sql-server database postgresql replication

I have a fairly good feel for what MySQL replication can do. I'm wondering what other databases support replication, and how they compare to MySQL and others?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.