Javascript 将 id - 视图传递给控制器​​ -

Javascript pass id - view to controller -

这在我的 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 出路,它也会对我有帮助!

查看:-

<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;
}