Reputation: 15207
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.
Upvotes: 1
Views: 3140
Reputation: 852
Simply use as follows
<?php $username = $this->input->post('username');?>
<?php $password= $this->input->post('password');?>
You can do anything with above variables
Upvotes: 0
Reputation: 1310
I guest we could use normal request, it's defend on the request type from ajax, using GET or POST, and then in the php we could use like normal post, like $_POST['username']
or $_GET['username']
we don't have to use function to unserialize that, and for validation using CI just call like normal use, $this->input->post('username')
,am i wrong ?
Upvotes: 0
Reputation: 31641
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()});
Upvotes: 3
Reputation: 28936
$parameters = array();
foreach ( explode( '&', $ajax ) as $parameterAndValue ) {
list ( $parameter, $value ) = explode( '=', $parameterAndValue );
$parameters[$parameter] = $value;
}
Upvotes: 1
Reputation: 13883
Use parse_str()
http://php.net/manual/en/function.parse-str.php
Upvotes: 1
Reputation: 76003
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'];
Upvotes: 4