pass variable from javascript function to controller method in codeigniter

做~自己de王妃 提交于 2019-12-24 18:53:26

问题


I'm new in CodeIgniter. I am making a project in which I make a javascript function in view an in this I define a variable .. it looks like this

var $rowCount=0;
function invest() {
  $rowCount=$('#ulinvestment').find('.rowInvestment').length;
}

my controller function contains

function input(parameter //i want to pass $rowcount value here ){
$this->load->helper('form');
$this->load->helper('html');
$this->load->model('mod_user');
$this->mod_user->insertdata();
 }

I want to access the variable $rowCount in controller function, how can I do that?


回答1:


Just to make sure I understand you, You are trying to pass a variable from javascript to CodeIgniter's controller function, right?

If that's your case(hopefully it is), then you can use AJAX, or craft an anchor link.

First of all, you're going to use the URI class, specifically the segment() function.

Let's assume this is your controller:

class MyController extends CI_Controller
{
    function input(){
    $parameter = $this->uri->segment(3);//assuming this function is accessable through MyController/input

    $this->load->helper('form');
    $this->load->helper('html');
    $this->load->model('mod_user');
    $this->mod_user->insertdata();
    }
}

Now with javascript you can either craft an anchor tag, or use AJAX:

Method 1: By crafting an anchor tag:

<a href="" id="anchortag">Click me to send some data to MyController/input</a>


<script>

var $rowCount=0;
function invest() {
  $rowCount=$('#ulinvestment').find('.rowInvestment').length;
}
$('#anchortag').prop('href', "localhost/index.php/MyController/input/"+$rowCount);
</script>

Method 2: By using AJAX:

var $rowCount=0;
function invest() {
  $rowCount=$('#ulinvestment').find('.rowInvestment').length;
}
//Send AJAX get request(you can send post requests too)
$.get('localhost/index.php/MyController/input/'+$rowCount);


来源:https://stackoverflow.com/questions/15716265/pass-variable-from-javascript-function-to-controller-method-in-codeigniter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!