Serialized array in controller
-
10-10-2020 - |
Question
This is my script
<script>
function callAjax(){
var customoptionhtml = document.getElementById("customoption-dynamic").innerHTML; //alert(test);//alert(jQuery(test).text());
var subtotalhtml = jQuery('.price-wrap').html();//alert(innerHtml);
jQuery.ajax({
type : "POST",
url : "<?php echo Mage::getUrl('module/controller/action'); ?>",
data : jQuery('#product_addtocart_form').serialize(),
data : { customoption: customoptionhtml,formser:jQuery('#product_addtocart_form').serialize(),subtotal:subtotalhtml } ,
dataType: "json",
complete: function(response) {
//action
},
});
}
</script>
This is my controller
public function testAction() {
$product = $this->getRequest()->getParam('formser');
$customoption = $this->getRequest()->getParam('customoption');
$pdctname = $product['product'];
Mage::log($product, null, '1.log');
Mage::log($customoption, null, '2.log');
}
I got $product in log file as :
form_key=ZWdfUerRFgl9oR4r&product=1&related_product=&options%5B9%5D=tryty&options%5B10%5D=85&options%5B11%5D=132&options%5B12%5D=156&options%5B13%5D=181&options%5B16%5D=&options%5B17%5D=&options%5B19%5D=&options%5B18%5D=&options%5B14%5D=183&options%5B15%5D=&name=ry&companyname=ty&email=test%40test.com&phnmbr=7894561233
I want to get "product=1"(marked in bold) from the above data(that is the product id).
I tried as $pdctdet = $product['product'];
.But not working.
Please give a solution.
Solution
Try this:
Use this in your controller:
$data = $this->getRequest()->getPost();
parse_str($data['formser']);
$productid = $product;
"product=1" will be in $productid variable.
OTHER TIPS
As per your log $product
contains as a string. if you need $productId
then you need to convert this string like below.
$product = "form_key=ZWdfUerRFgl9oR4r&product=1&related_product=&options%5B9%5D=tryty&options%5B10%5D=85&options%5B11%5D=132&options%5B12%5D=156&options%5B13%5D=181&options%5B16%5D=&options%5B17%5D=&options%5B19%5D=&options%5B18%5D=&options%5B14%5D=183&options%5B15%5D=&name=ry&companyname=ty&email=test%40test.com&phnmbr=7894561233";
$products = explode("&",$product);
foreach($products as $string){
list($k, $v) = explode('=', $string);
$result[ $k ] = $v;
}
echo $productId = $result['product']; // 1