Sunday, January 24, 2010

Re: [jQuery] JQuery Ajax serialize

Use parse_str(). But beware that that string has a problem:

<?php
header('Content-type: text/plain');
$str = 'single=Single&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio1';

/* old school way: explode() into pairs, then explode each of those into
* key => val
*/
$pairs = explode('&', $str);

foreach($pairs as $pair)
{
$parts = explode('=', $pair);
echo "key: ${parts[0]} -- val: ${parts[1]}\n";
}

echo "\n-------\n";

/* better way: parse the string into variables
*/
parse_str($str);

echo "${single}\n"; // 'Single'
echo "${multiple}\n"; // 'Multiple3' -- whoops! It takes the last value
echo "${check}\n"; // 'check2'
echo "${radio}\n"; // 'radio1'

echo "\n-------\n";

/* parse values into array instead
*/
parse_str($str, $arr);

foreach($arr as $slice)
{
echo "${slice}\n"; // will get 'Array' for multiples
}


echo "\n-------\n";

/* multiple element names should have '[]'
*/
$str = 'single=Single&multiple[]=Multiple&multiple[]=Multiple3&check=check2&radio=radio1';

parse_str($str, $arr);

foreach($arr as $var)
{
if (is_array($var))
{
foreach($var as $m)
{
echo "${m}\n";
}
}
else
{
echo "${var}\n";
}
}

On Sat, Jan 23, 2010 at 1:39 PM, parot <russell@parotkefalonia.com> wrote:
>
> I know this may be a silly question, but is there a "magic" way to insert
> post data via serialization into a php/mysql database?
>
> e.g. a serilized array of
> single=Single&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio1
>
> yes I used the Jquery serialize page info as an example.
>
> Is is best to use PHP to explode the array? or what?
>
> Or as asked is there a "magic" way to split the array into the fields &
> values?
> --
> View this message in context: http://old.nabble.com/JQuery-Ajax-serialize-tp27288727s27240p27288727.html
> Sent from the jQuery General Discussion mailing list archive at Nabble.com.
>
>

No comments: