我需要使用ajax提交表单数据并获取提交记录的自动增量ID并将其显示在div上
这是我的代码
控制器
<?php
class Form_controller extends CI_controller{
function index(){
$this->load->view('submit_form');
}
public function insert_into_db(){
$this->load->model('form_model');
$this->form_model->insertQ();
} }
查看
<html>
<body>
<form method="post" name="myForm1" id="myForm1" enctype="multipart/form-data" >
Email: <input type="text" name="email" id="email">
Question: <input type="text" name="qText" id="qText">
<input id="submitbutton" type="submit">
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script> //no need to specify the language
$(function(){
$("#submitbutton").click(function(e){ // passing down the event
$.ajax({
url:"<?php echo site_url('form_controller/insert_into_db'); ?>",
type: 'POST',
data: $("#myForm1").serialize(),
success: function(){
alert("success");
$('#email').val('');
$('#qText').val('');
},
error: function(){
alert("Fail")
}
});
e.preventDefault(); // could also use: return false;
});
});
</script>
</body>
</html>
模型
<?php
class Form_model extends CI_Model{
function insertQ(){
$email = $this->input->post('email');
$qText = $this->input->post('qText');
$this->db->insert('questions', array('email' =>$email, 'text' => $text));
} }
我已经尝试了几次,但无法修复它,我是codeigniter以及ajax的新手
答案 0 :(得分:1)
你做错了。您将在模型函数中而不是在控制器函数中获取变量。
之后,您的控制器功能将如下:
<?php
class Form_controller extends CI_controller{
function index(){
$this->load->view('submit_form');
}
public function insert_into_db(){
$this->load->model('form_model');
$this->form_model->insertQ($this->input->post('email'),$this->input->post('qText')));
您的模型功能将是:
<?php
class Form_model extends CI_Model{
function insertQ($email, $qtext){
$this->db->insert('questions', array('email' =>$email, 'text' => $text));
}