[英]How to pass variable from Controller to View with Ajax in Codeigniter?
[英]codeigniter sending a variable from ajax to controller
我目前正在做ajax添加,更新和删除。 而且我认为我将从删除开始,因为它是最简单的方法,希望对其他人有所帮助。
在jquery中(这在$ doc.ready内部,并且事件已正确触发)
if ($a == "Delete")
{
var postid = $(this).next('.postid').val();
$(this).closest(".todo-content").fadeOut();
jQuery.ajax({
type: "POST",
dataType: 'json',
url: "<?=base_url()?>.index.php/classes/deletepost",
data: {postid: postid},
async: false,
});
}
在HTML
<form method="post">
<button class="btn" onclick="return confirm('Are you sure to delete this item?')">Delete</button>
<input type="hidden" value="<?php echo $id; ?>" name="postid">
</form>
在控制器中
public function deletepost(){
$id = $this->input->post('postid');
$data = array('active' => 0);
$this->Model_name->deletepost($id,$data);
redirect('/abc/123');
}
这已经在起作用,但随后我计划将其添加到ajax中。 我正在尝试将postid
从ajax传递到控制器以删除此帖子。 fadeout
已经可以使用,但只有Ajax无效。 我对ajax还是很陌生,所以我不知道我要去哪里错了,我可能还会再问有关crud其他部分的问题。
固定!
问题是$.ajax
的url。 它返回一个垃圾。
所以我在标题中添加了一个脚本
<script type="text/javascript">
var BASE_URL = "<?php echo base_url();?>";
</script>
只需在url:
使用BASE_URL
url:
就像url: BASE_URL+'classes/deletepost',
请尝试遵循以下步骤:
在Codeigniters视图中:
<!-- Store ID and baseurl as attributes . this would help you to fetch data -->
<button class="btn" postId="5" baseUrl="<?php echo base_url();?>" id="button">Delete</button>
<!-- Store ID and baseurl as attributes . this would help you to fetch data -->
<button class="btn" postId="5" baseUrl="<?php echo base_url();?>" id="button">Delete</button>
<!-- reading jquery file .. -->
<script type="text/javascript" src="http://localhost/jquery/js_search/jquery.js"></script>
<!--you can write file in extra js file .. it depends on you -->
<script type="text/javascript">
$('#button').click(function(){
// ask for confirmation
var result = confirm("Want to delete?");
// if it is confirmed
if (result) {
// get baseURL and ID using attributes
var base_url = $('#button').attr('baseUrl');
var postid = $('#button').attr('postId');
// make a ajax request
$.ajax({
url: base_url,
type: "POST",
dataType: 'json',
success: function (data) {
if(data){
// Fade out the content id
$('#content_id').closest(".todo-content").fadeOut();
}
}
});
}
});
</script>
在控制器中:
// You just need to delete the post and return a status code of "200"
public function deletepost(){
$id = $this->input->post('postid');
$data = array('active' => 0);
$this->Model_name->deletepost($id,$data);
redirect('/abc/123');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.