I am creating a codeigniter project where i get number of items from my database and each item has a submit button clicking on which the data are stored into the database using AJAX and jQuery. Now, the problem is that when i submit any item only the data of 1st form is sent to the method that inserts data to the database please provide some solution regarding the same. my code is as under:
Model:
<?php
class Products_model extends CI_Model{
function get_all(){
$results = $this->db->get('tblUtensils')->result();
return $results;
}
function get($id){
$results = $this->db->get_where('tblUtensils', array('pkItemID' => $id))->result();
$result = $results[0];
return $result;
}
}
?>
View:
<body>
<div id="products">
<?php foreach ($products as $product):
$id=$product->pkItemID;
?>
<li>
<?php echo form_open('shop/add', 'id="form"'); ?>
<div><?php echo form_input('name_' . $id, $product->fldName , 'id='.'"'.'name_' . $id.'"');?></div>
<div><?php echo form_input('desc_' . $id, $product->fldDescription , 'id='.'"'.'desc_' . $id.'"');?></div>
<div><?php echo form_input('rate_' . $id, $product->fldRateMB1 , 'id='.'"'.'rate_' . $id.'"');?></div>
<div><?php echo form_input('Qty_' . $id, 0, 'id='.'"'.'qty_' . $id.'"');?></div>
<?php echo form_hidden('id', $product->pkItemID, 'id="ID"'); ?>
<?php echo form_submit('action', 'Add','id="submit"');?>
<?php echo form_close(); ?>
</li>
<?php endforeach; ?>
</ul>
</div>
<!-- try 2 -->
<script type = "text/javascript">
$(function(){
$('form').submit(function(e){
e.preventDefault(); // <------this will restrict the page refresh
var form_data = {
id: $('#id').val(),
name: $('#name_' + id).val(),
rate: $('#rate_' + id).val(),
qty: $('#qty_' + id).val()
};
$.ajax({
url: "<?php echo site_url('shop/add'); ?>",
type: 'POST',
data: form_data,
success: function(msg) {
alert("success");
}
});
return false;
});
});
</script>
</body>
</html>
Controller:
<?php
class Shop extends CI_Controller{
function index(){
$this->load->model('Products_model');
$data['products'] = $this->Products_model->get_all();
$this->load->view('products',$data);
}
function add(){
//$this->load->model('Products_model');
//$product = $this->Products_model->get($this->input->post('id'));
$insert = array(
'id' => $this->input->post('id'),//<-- also not able to get this id from ajax post request
'qty' => $this->input->post('qty'),
'price' => $this->input->post('rate'),
'name' => $this->input->post('name'),
);
$this->cart->insert($insert);//<--insert item into cart
$query// to insert into database
//redirect('shop');
}
}
?>
Many questions have been posted before regarding codeigniter and ajax but none did provide solution to my problem so i am posting this question, appreciate your help.