[英]CodeIgniter: Pass Javascript Array from View to Controller then store to Database
I'm trying to post a javascript array to a controller function in codeigniter then store it into the database via AJAX. 我正在尝试将JavaScript数组发布到codeigniter中的控制器函数,然后通过AJAX将其存储到数据库中。 I have no problem when passing single values, and this is the first time i'm passing an array. 传递单个值时我没有问题,这是我第一次传递数组。
Here's the code 这是代码
//JAVASCRIPT IN THE VIEW (students variable already populated and classCode already has a value)
$.ajax({
traditional: true,
type: 'POST',
url: '<?php echo base_url(); ?>index.php/ams_controller/recordAbsence',
data: 'classCode='+classCode+'&students='+students,
success: function(resp) {
alert("Absences Saved");
}
});
//CONTROLLER FUNCTION
public function recordAbsence() {
$temp=getdate(date("U"));
$date = $temp[month] ." ". $temp[mday] ." ". $temp[year];
$classCode = $this->input->post('classCode');
$students = $this->input->post('students');
$this->load->model('model_users');
if($this->model_users->recordAbsence($classCode, $students, $date)) {
return true;
} else{
return false;
}
}
//MODEL FUNCTION
public function recordAbsence($classCode, $students, $date) {
foreach($students as $row) {
$data = array(
'stud_no' => $row,
'date_of_absence' => $date,
'classCode' => $classCode
);
$query = $this->db->insert('absence', $data);
}
if($query) {
return true;
} else {
return false;
}
}
The data isn't being stored in the absence table. 数据未存储在缺席表中。 Any help would be appreciated. 任何帮助,将不胜感激。
Pass data like object: 像对象一样传递数据:
data: {classCode: classCode, students: students},
Edit: Also, googling for existing question under "jquery ajax passing array" would give you this as first link. 编辑:此外,谷歌搜索下“ jquery ajax传递数组”下的现有问题会给你这个作为第一个链接。 Check first two answers there too. 在那里也检查前两个答案。
Edit: 20160525171759 编辑:20160525171759
You can pass JSON stringified array JSON.stringify(array)
and manipulate it with json_decode($this->input->post('postKey'))
. 您可以传递JSON字符串化数组JSON.stringify(array)
并使用json_decode($this->input->post('postKey'))
。
//JS
//students = ["2014-52307", "2014-26571", "2014-68959", "2014-60379", "2014-56077"];
students = JSON.stringify(students);
//check if same is needed for classCode variable since I don't know if classCode is array too
$.ajax({
//I removed traditional property to pass an object
type: 'POST',
//I put URI as method argument (check if index.php is sufficient)
url: '<?php echo base_url("index.php/ams_controller/recordAbsence"); ?>',
data: {classCode: classCode, students: students},
success: function(resp) {
alert("Absences Saved");
}
});
//PHP
$students = $this->input->post('students');
//echo $students;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.