I want to post a form using AJAX for that I have created a form and I working fine when I put this two lines of code in my controller:
$this->Security->config('unlockedFields', ['product_id']);
$this->Security->config('unlockedActions',array('update'));
if remove this code I get
Error:Bad Request in console.
<?php echo $this->Form->create('Cart',array('id' => 'saveForm'));
$total=0;
foreach ($products as $product):
echo $product['product_name'];
echo $this->Form->input('product_id.',array('value'=>$product['product_id'],'type' => 'number'));
echo $this->Form->input('count.',array('type'=>'number', 'label'=>false,
'class'=>'form-control input-sm', 'value'=>$product['count']));
echo $product['count']*$product['product_price'];
endforeach;
echo $total;
echo $this->Form->submit('Save');
echo $this->Form->end();
?>
Controller Action:
public function update() {
$this->autoRender = false;
if (!empty($this->request->data)) {
$cart = array();
foreach ($this->request->data['count'] as $index=>$count) {
if ($count>0) {
$productId = $this->request->data['product_id'][$index];
$cart[$productId] = $count;
}
}
$this->Carts->saveProduct($cart);
$carts = $this->Carts->readProduct();
$products = array();
if (null!=$carts) {
foreach ($carts as $productId => $count) {
$product = $this->Products->get($productId);
$product['count'] = $count;
$products[]=$product;
}
}
$this->set('products', $products);
$this->render('cart_view');
$this->set(compact('products'));
}
}
index.ctp
$(document).on("submit", "#saveForm", function(ev) {
var formData = $('#saveForm').serialize();
var formUrl ="http://localhost/multi_shopping/Singles/update";
$.ajax({
type: 'POST',
url: formUrl,
data: formData,
dataType: 'html',
async : false,
success: function(data,textStatus,xhr){
$('#PPMiniCart').html('');
$('#PPMiniCart').html(data);
$('#PPMiniCart').show();
},
error: function(xhr,textStatus,error){
alert("error"+error);
}
});
ev.preventDefault();
return false;
});