Reputation: 29
The data (array of array) is not getting passed from view to controller while using AJAX in CodeIgniter (PHP)
url is working in $.ajax. It is redirecting to the method in controller
view.php (view)
$('#save').click(function(){
var table_data = [];
// use .each to get all data
$('#data_table tr').each(function(row,tr){
// create array again to store data by row
// get only data with value
if ($(tr).find('td:eq(0)').text() == "") {
} else {
var sub = {
'no' : $(tr).find('td:eq(0)').text(),
'firstname' : $(tr).find('td:eq(1)').text(),
'middle' : $(tr).find('td:eq(2)').text(),
'last' : $(tr).find('td:eq(3)').text(),
};
table_data.push(sub);
}
});
//use ajax to insert the data
console.log(table_data);
var data = {'data_table':table_data};
console.log(data);
$.ajax({
data : data,
type : 'POST',
url : 'save',
crossOrigin : false,
dataType : 'array',
success: function(msg){
$('.answer').html(msg);
}
});
Welcome.php (controller)
public function save() {
$relatives_list = $this->input->post('data');
echo 'as';
echo $relatives_list;
// the list is not shown here
$this->load->model('Batch');
$status = $this->Batch->save($relatives_list);
$this->output->set_content_type('application/json');
echo json_encode(array('status' => $status));
}
Batch.php (model)
public function save($relative_list){
$length = count($relative_list);
for($x = 0; $x < count($relative_list); $x++){
$data[] = array(
'no' => $relative_list[$x]['no'],
'firstname' => $relative_list[$x]['firstname'],
'middle' => $relative_list[$x]['middle'],
'last' => $relative_list[$x]['last'],
);
}
try {
for($x = 0; $x<count($relative_list); $x++){
$this->db->insert('hhh',$data[$x]);
}
return 'success';
}catch(Exception $e) {
return 'failed';
}
}
Error:
parameter-must-be-an-array-or-an-object-that-implements-countable
Upvotes: 2
Views: 207
Reputation: 9265
According to your script it wouldn't be data
it would be data_table
var data = {'data_table':table_data};
Thus:
var_dump($this->input->post('data_table')
If that doesn't work please post the console.log
of your data
var.
Please note: you will have to remove the echos
before json_encode
after you are done troubleshooting or jquery will fail to parse the response.
Upvotes: 1