简体   繁体   中英

CodeIgniter get id parameter when using ajax

When I open a specific customer form, my url changes to something like this:

http://localhost/proj/dashboard/customers/edit/1

As you can see there's a parameter with the ID (which in this case is 1). Now, I would like to get this ID on my controller when I call my ajax OR before calling my ajax.

Currently, my ajax is the following:

$.post("ajax_edit", {name: _name, age: _age, function(aux){
   console.log(aux);
});

Which does not send any parameter with the ID. I was hoping that I might get it by PHP.

print_r($this->uri->segment_array());
/* output:  
Array
(
    [1] => dashboard
    [2] => customers
    [3] => edit
    [4] => ajax_edit
) */

But unfortunatelly that's what shows to me. So, how can I get that value?

Alternatively you can use php script inside your javascript.

$.post("ajax_edit", {name: _name, age: _age, obj_id: <?php echo $this->uri->segment(4); ?>, function(aux){
   console.log(aux);
});

In your route.php config

$route['dashboard/customers/edit/(:num)'] = "customers/edit/$1";

In your customer.php controller

public function edit($user_id) {

    $data['user_id'] = $user_id;
    $this->load->view('NAME_OF_VIEW_FILE', $data);
}

In your view file

$.post("ajax_edit", {user_id: <?= $user_id ?>, name: _name, age: _age, function(aux){
   console.log(aux);
});

I think it's a proper way thant using sessions or playing with uri_segments.

Solved in a different way. Although I really do believe it isn't the best option, I used a session variable.

So in the controller function edit:

public function edit(){
  // all code
  $this->session->set_userdata('obj_id', $this->uri->segment(4)); // which is the ID of the customer 
}

And then in the ajax_edit function I just have to call that session item.

public function ajax_edit(){
  $id = $this->session->userdata('obj_id');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM