Split POST array into multiple variables
Question by methuselah
I’m coding a form right now using jQuery .post and the file responsible for processing has the code:
print_r($_POST);
Which returns the following dynamic output:
Array ( [data] => capacity=50-1000+people&bookingdate=17%2F04%2F2012&grade=1+star )
I am trying to split up this array into three variables namely capacity, booking date and grade but don’t really know how to. Any idea how? I’ve tried using echo $_POST[“capacity”]; but it doesn’t work.
Thanks in advance!
Edit
This is the jQuery I’m using:
<script type="text/javascript">
$(document).ready(function() {
$("#postData").click(function() {
$("#last-step").hide(600);
$.post('resources/process2.php', { data: $("#task5_booking").serialize() }, function(data) {
$("#result").html(data);
});
return false;
});
});
</script>
which is working with the following form:
Answer by Salman A
I think you should change this line:
$.post('resources/process2.php', { data: $("#task5_booking").serialize() }, function(data) {
To
$.post('resources/process2.php', $("#task5_booking").serialize(), function(data) {
Notice that I changed the second parameter from an object literal to a (url-encoded) string. This posts each variable in your form as a separate variable (as if it were posted directly). On the server side, each variable should be available separately inside $_POST
array.
Answer by Starx
You have to use explode for this.
$data = array(); // A array to store the extracted value
$temp = explode("&", $data); // First of all explode by "&" to get the each piece
foreach($temp as $tval) {
$t = explode('=', $tval); // Next explode by "=" to get the index and value
$data[$t[0]] = $t[1]; //Add them to the array
}
Another alternative is to use parse_str():
$data = array();
parse_str($_POST['data'], $data);
After this all the values will be mapped to the $data