4

I am using codeigniter-4 version and trying to auto search in nav bar. I'm trying to send data in post method into controller using ajax. But its not work. And codeigniter 4 don't described details for ajax. below my code sample input box is -

<input class="form-control mr-sm-2" type="search" placeholder="<?= lang('nav.search'); ?>" aria-label="Search" name='s' id="seachBox">

ajax code is -

     $.ajax({  
       url:<?= base_url('search'); ?>,
       headers:{'X-Requested-With':'XMLHttpRequest'},
       data:{query:query},
       success:function(data){
             alert(data);
       }  
    });

and my controller is -

<?php
class Search extends BaseController
{
    public function __construct()
    { 
        helper(['common_helper','aws_helper']);
    }

    public function index(){

        echo 'string';
    }
}
?>

route is -

<?php 

$routes->get('/search', 'Search::index');

?>
Shahadat
  • 151
  • 2
  • 3
  • 14

1 Answers1

11

Here is the sample code of ajax. (Make sure that you have defined route/controller method for search url)

$.ajax({  
    url:<?php echo base_url('search'); ?>,
    type: 'post',
    dataType:'json',
    data:{query:query},
    success:function(data){
        alert(data);
    }  
});

CI4 Code to get the request data

if ($this->request->isAJAX()) {
    $query = service('request')->getPost('query');
    var_dump($this->request->getPost('query'));
}

Also, make sure to update csrf token on every request if you are not reloading a page on success. Also, you need to return csrf token in method. So in that case your method will look like -

if ($this->request->isAJAX()) {
        $query = service('request')->getPost('query');
        //var_dump($this->request->getPost('query'));
        return json_encode(['success'=> 'success', 'csrf' => csrf_hash(), 'query ' => $query ]);
    }

So in that case your ajax code will look like -

$.ajax({  
        url:<?php echo base_url('search'); ?>,
        type: 'post',
        dataType:'json',
        data:{query:query},
        success:function(data){
           var result = JSON.parse(data);
            $("input[name='csrf_test_name']").val(result['csrf']);
        }  
    });
Abhishek Honrao
  • 780
  • 5
  • 28
Jitendra Kumar
  • 382
  • 3
  • 14