Home > Enterprise >  codeigniter dynamically passing page url not working after page reload
codeigniter dynamically passing page url not working after page reload

Time:10-08

in my codeigniter website, i have created a products page and display products in it using the category name in the url:

<?php foreach($category as $cat){?>
<li><a href="<?php echo base_url()?>homecontroller/products/<?php echo $cat->name;?>"><?php echo $cat->name;?></a></li>
<?php }?>
this is working fine. now to filter the products i did the following in my controller :

public function products()
      {
$id =$this->uri->segment(3);
$material=$this->input->post('material1');       
$material2=$this->input->post('material2');
$data['products'] = $this->product->findAll($id,$material,$material2);
$this->load->view('products', $data);
      }

my model:

function findAll($id,$material,$material2)
{
$this->db->where('cname', $id);
if(!empty($material) || !empty($material2)) {
$this->db->or_where('material', $material);
$this->db->or_where('material', $material2);
}
return $this->db->get('product')->result();
}

and my filter product view:

<form action="<?php echo base_url()?>products" method="post">
<input type="checkbox" name="material1" value="cotton" class="form-check-input filled-in" id="new" onChange="this.form.submit()">
<input type="checkbox" name="material2" value="polyster" class="form-check-input filled-in" id="used" onChange="this.form.submit()">
</form>

here the problem is when a user select the filter option the page reloads and does the filter fine but the url becomes my base url/products which makes the product page to display all products without category, can anyone please tell me how to fix this, thanks in advance

CodePudding user response:

try to use site_url instead of base_url in your view,base_url returns the base URL from your configuration site_url give a correct URL with index.php

  <form action="<?php= site_url('homecontroller/products')?>" method="post">
<input type="checkbox" name="material1" value="cotton" class="form-check-input filled-in" id="new" onChange="this.form.submit()">
<input type="checkbox" name="material2" value="polyster" class="form-check-input filled-in" id="used" onChange="this.form.submit()">
</form>

try to use it here also
<?php foreach($category as $cat){?>
    <li><a href="<?= site_url('homecontroller/products/'.$cat->name)?>"><?= $cat->name;?></a></li>
    <?php }?>

you should consider retrieving the passed values in the URL as a function parameter like this

public function products($productName)
{
     $id = $productName;
     $material = $this->input->post('material1');       
     $material2 = $this->input->post('material2');
     $data['products'] = $this->product->findAll($id,$material,$material2);
     $this->load->view('products', $data);
}

I hope it solves your problem

CodePudding user response:

Also try

<form method="post">

without action attribute to keep current url.

  • Related