daryl
daryl

Reputation: 15207

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.

Upvotes: 1

Views: 3140

Answers (6)

Srihari Goud
Srihari Goud

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

Khairu Aqsara
Khairu Aqsara

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

Francis Avila
Francis Avila

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

George Cummins
George Cummins

Reputation: 28936

$parameters = array();

foreach ( explode( '&', $ajax ) as $parameterAndValue ) {
    list ( $parameter, $value ) = explode( '=', $parameterAndValue );
    $parameters[$parameter] = $value;
}

Upvotes: 1

Jordan Brown
Jordan Brown

Reputation: 13883

Use parse_str()

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

Upvotes: 1

Jasper
Jasper

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

Related Questions