Codeigniter pass a id to controller from view

2019-05-31 06:08发布

问题:

I am using codeigniter for this project. I hava a id value in which i pass from controller A to view A. This id value is echo between an anchor tag. When this anchor tag is clicked on, it redirects to another controller B with the id value and processed this id value within controller B. Is there any other way of doing this other than using the uri class? Want to keep the url clean.

I thought of a way of appending hidden input elements when I shift from controller A to view A to controller B, but i realised it can be very messy.

Any clean ways of doing this? Thanks in advance guys!

回答1:

New to using Stackoverflow See if you could understand my layout:

METHOD 1

Use the URI Class except you have good reasons not to.

From CONTROLLER_A

$data["id"] = ("ID NUMBER");
$this->load->view("VIEW_A", $data);

ANCHOR IN VIEW A

<a href="<?php echo base_url() ?>/controller_b/controllerfunction/<?php echo $id ?>">link</a>

IN CONTROLLER_B

$id = $this->uri->segment(3);

.

METHOD 2

USE FORM POST if you want to keep things hidden:

$data["id"] = ("ID NUMBER");
$this->load->view("VIEW A", $data);

ANCHOR IN VIEW A

<form name="myform" id="myform" action="<?php echo base_url() ?>/controllerB/controllerfunction/" method="post">
<input type="hidden" name="id" id="id" value="<?php echo $id ?>" />
<input type="submit" value="See more" />
</form>

You could also use javascript to submit the form here via link if you which:

 <a href="javascript;" onclick="document.getElementById('myform').submit();"> See more</a>

Tips:You could also use css to hide submit button in the form by setting opacity to 0; If link is within the form, you could use javascript:this.submit();

OR JQUERY

<a href="javascript;" id="link">See more</a>
$('#link').click(function() {
    $('#myform').submit();
});

IN CONTROLLERB

$id = $this->input->post("id");


回答2:

Well hidden inputs will work, and there's may another workaround that once you redirected to the method and use your id value i.e. get data from database, redirect again to another controller method with the clean URL you need , hope this is helpful



标签: codeigniter