[英]how can i insert database record when a button is clicked - Codeigniter, jquery, ajax
所以这是我的问题,我正在学校项目中创建自己的upvote和downvote功能。 我想要发生的一切是,当我单击向上箭头图像时,它将插入一条记录到数据库。 它将为我数据库中的表添加一个记录。
<script type="text/javascript">
$( document ).ready(function() {
$("#try").click(function(){
var username = $("#username").val();
var thread_id = $("#thread_id").val();
var vote = $("#vote").val();
$.ajax(
{
type:"post",
url: "<?php echo site_url();?>/Users/add_vote/",
data:{ username:username, thread_id:thread_id, vote:vote},
success:function(data)
{
alert("POST SUBMITTED");
}
});
});
});
这是我的表格
<div id = "active_upvote_div">
<form>
<input type="hidden" name = "username" id="username" value= "try">
<input type="hidden" name="thread_id" id="thread_id" value= "1">
<input type="hidden" name="vote" id="vote" value= "1">
<button type="submit" id="try"><img src="<?php echo base_url();?>/public/images/upvote.png" height:"25px" width="25px"/> </button>
</form>
</div>
我的控制器仅调用模型
这是我的模特
public function ajax()
{
$add_user = array(
'username' => $this->input->post('username'),
'thread_id' => $this->input->post('thread_id'),
'vote' => $this->input->post('vote'),
);
$this->db->insert('thread_upvote', $add_user);
}
希望立即作出回应:(
在codeigniter中, $this->input->post()
等同于$_POST
,它将发布的名称数组作为key/value
对。
在controller's add_vote()
函数中执行此操作...
public function add_vote()
{
$data = $this->input->post();
$this->load->model('model_namel');//loads model
$this->model_name->ajax($data);//call model's function with data
}
然后在model's ajax()
函数中
public function ajax($data=array())
{
$this->db->insert('thread_upvote', $data);// inserts into database
}
在您的Ajax中:
$( document ).ready(function() {
$("#active_upvote_div").click(function(){
var username = $("#username").val();
var thread_id = $("#thread_id").val();
var vote = $("#vote").val();
$.ajax({
type:"POST",
dataType: 'json', //add this to call json
url: "<?php echo site_url();?>/Users/add_vote/",
data:{ username:username, thread_id:thread_id, vote:vote},
success:function(data)
{
if(data.success == true){
alert("POST SUBMITTED");
} else{
alert("Failed to Post");
}
}
});
});
});
在您的控制器中:
Class Users extends CI_Controller{
public function add_vote()
{
$result = $this->name_of_model->ajax(); //call the ajax function in you model
echo json_encode($result); //check the return if true or false and pass to json
}
}
在您的模型中:
public function ajax()
{
$add_user = array(
'username' => $this->input->post('username'),
'thread_id' => $this->input->post('thread_id'),
'vote' => $this->input->post('vote'),
);
if($this->db->insert('thread_upvote', $add_user))
{
return true;
} else{
return false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.