Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call function inside CodeIgniter's controller using jquery / ajax

Can somebody please explain to me what is the right way to call a php function with jquery / ajax in Codeigniter. Right now, this code isn't working and i cant figure out whay. Note that admin.php controler is inside admin map. Thanks in advance

html code

<form action="#" method="POST" id="change">
             <input type="hidden" value="<?php echo $row->id_product; ?>" id="prod" >    
             <input type="submit" value="switch" >
</form>
<div class="resultdiv">
    <?php echo $data; ?>
</div>

my function inside admin.php controller

 public function do_search(){
        $id = $this->input->post('id');
        return $id;
    }

Jquery AJAX script

$( "#change" ).submit(function() {
  alert( "Change" );
  var id = $('#prod').val();
     $.ajax({
            type:'POST',
            url:'admin321/do_search',
            data:{'id':id},
            success:function(data){
                $('#resultdiv').html(data);
            }
        });
});

Config / routes.php

$route['admin/do_search'] = "admin_controller/admin/do_search";
like image 852
Valor_ Avatar asked Dec 08 '22 09:12

Valor_


2 Answers

I know that this is old post, but maybe someone will find this usefull.

I solve this problem by adding index.php in url. Even if the index.php is hidden using rewrite.

  $( "#change" ).submit(function() {
      alert( "Change" );
      var id = $('#prod').val();
         $.ajax({
                type:'POST',
                url:'<?php echo base_url("index.php/admin/do_search"); ?>',
                data:{'id':id},
                success:function(data){
                    $('#resultdiv').html(data);
                }
            });
    });
like image 99
Brane Avatar answered Dec 11 '22 11:12

Brane


Maybe like this:

    $( "#change" ).submit(function() {
  alert( "Change" );
  var id = $('#prod').val();
     $.ajax({
            type:'POST',
            url:'<?php echo base_url("admin/do_search"); ?>',
            data:{'id':id},
            success:function(data){
                $('#resultdiv').html(data);
            }
        });
});

You have to load this helper:

$this->load->helper('url');

@edit

$route['admin/do_search'] = "admin_controller/admin/do_search";

This code is unnecessary.

like image 23
ajtamwojtek Avatar answered Dec 11 '22 11:12

ajtamwojtek