1

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.

daryl
  • 14,307
  • 21
  • 67
  • 92

6 Answers6

4

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'];
Jasper
  • 75,717
  • 14
  • 151
  • 146
3

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()});
Francis Avila
  • 31,233
  • 6
  • 58
  • 96
1

Use parse_str()

http://php.net/manual/en/function.parse-str.php

Jordan Brown
  • 13,603
  • 6
  • 30
  • 29
1
$parameters = array();

foreach ( explode( '&', $ajax ) as $parameterAndValue ) {
    list ( $parameter, $value ) = explode( '=', $parameterAndValue );
    $parameters[$parameter] = $value;
}
George Cummins
  • 28,485
  • 8
  • 71
  • 90
0

Simply use as follows

<?php $username = $this->input->post('username');?>
<?php $password= $this->input->post('password');?>

You can do anything with above variables

Srihari Goud
  • 824
  • 10
  • 25
0

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 ?

Khairu Aqsara
  • 1,321
  • 3
  • 14
  • 27