从jQuery调用Controller函数

I'm working on some codes. Here's my code

jQuery

duration = 30;
var countdown = setInterval(timer,1000);
var url = window.location.origin + '/pro/index.php/Test';

function timer(){
  duration = duration - 1; 
  if(duration<=0){
    clearInterval(countdown);
    window.location(url+'/next');
  }
}

I want to redirect and run function in Test/next. In next() method, it will rule where the link should go. url helper also has been added automatically in Loader

Controller

public $num;
public $val;

public function index(){
  // get the value from GET method
  $this->num = $this->input->get('num');
  $this->val = $this->input->get('val');
}

public function next(){
  $x = $this->num;
  $x = $x + 1;
  if($x < 4){
    redirect(site_url('index.php/Test?x='.$x/.'&num='.$this->num));
  }
  else{
    // it will redirect to another page
    // redirect(site_url('index.php/Home'));
    echo 'x = '.$x.', num = '.$this->num;
  }

(The codes above have been simplified).

The method has been run, but the url was localhost/pro/index.php/Test/next and echo-ing :

x = , num =

It seems like the global property doesn't work for the function called from JS/jQuery. Any explanation or solution for this?

You can access controller function from view page to using base URL (Click here how to do it?). Then use jQuery Ajax call controller function.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

$.ajax({
    type: 'post', url: '<?php echo base_url("next");?>',
    data: {},
    success: function(result){
        console.log(result);
    }
});

You need ajax calling. In your View file

<button class="call_ajax" name="submit">Call Ajax</button>
    <script type="text/javascript">
        $('.call_ajax').click(function(){
        var value1 = 'some data';
        var value2 = 'some data'; 
        $.ajax({
            url: '<?php echo site_url('your_controller/your_function'); ?>',
            type: 'POST',
            data: {
                key1: value1,
                key2: value2
            },
            dataType: 'json',
            success: function(url) {
            window.location.href = url;
         }
        });
    });</script>

in your Controller

your_function(){
    $data1 = $this->input->post('key1');
    $data2 = $this->input->post('key2');
    // do Data Processing
    // For return some data ; 
    echo "https://some-webiste-url/";

    // FOR Array

    echo json_encode($any_data_array);

}

NOTE : controller Function called from ajax will not do redirection . If you want to direct to some other url , you have to do that in the Javascript Section Using