Javascript传递id -视图到控制器-



这在我的CodeIgniter函数中不起作用。因为我有id,但无法在控制器函数中获取id。我很困惑如何在Javascript和Ajax的方式做到这一点。

这是我的视图脚本

<script>
function delete_img_fn(id)
{ 
alert(id); // It gives '1','2',etc on clicking every row in table 
var r=confirm("Do you want to Delete");
if (r==true)
{
$.post("<?php echo site_url('/admincontent/delete_portfolioimg/');?>", {id:id},
function(data) {
alert(data+"a");
}, 'json');
}
else
{
x="You pressed Cancel!";
alert(x);
}      
}

</script>

,我正试图通过控制器函数发送我的id,如下所示:

public function delete_portfolioimg()
{ 
echo $this->input->post('id');exit('I am trying in controller function');
}

以上操作无效。我还尝试了下面的代码:

window.location.href = "<?php echo site_url('/admincontent/delete_portfolioimg/'.id);?>'?id="+id;
window.location.href = "<?php echo site_url('/admincontent/delete_portfolioimg/'.id);?>";

但是都不起作用…它也会帮助我,如果有人指导我如何在ajax的出路!

View:-

<a><img src="<?php echo base_url();?>adminassets/images/icons/deletered.png" alt="Alternate Text" onclick="del(<?php echo $result['image_id'];?>)"/> </a>

ajax代码是:

<script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<script>
function del(id)
{ 
if (confirm("Are you sure?")) {
$.ajax({
url: "<?php echo site_url(); ?>/admincontent/delete_portfolioimg/" + id,
type: 'POST',
data: {"id":id},
dataType: 'json',
success: function(response) {
alert('Image is deleted successfully now');
},
error: function () {
alert('Could not delete image');
}
});
} else {
alert(id + " not deleted");
}
}

控制器代码为:

public function delete_portfolioimg()
{  
$id = $this->input->post('id');
//print_r($id);exit('Dell');

$res = $this->admin_model->ch_portfolioimg($id); 
echo json_encode($res);
}

模型代码为:

public function ch_portfolioimg($id)
{    
$this->db->select('*');
$this->db->from('portfolio_img');
$this->db->where('image_id', $id); $res = $this->db->get()->row_array(); //echo '<pre>';print_r($res);exit('Change Portfolio Image');
if(!empty($res))
{
unlink($_SERVER['DOCUMENT_ROOT'].'/NetSach/assets/images/'.$res['image_url']);
}
$this->db->where('image_id', $id);
$this->db->delete('portfolio_img'); 
return true;
}

最新更新