PHP CodeIgniter Access Controller Require

I use codeigniter for my project and I am stuck trying to figure it out.

I have javascript that needs to make an AJAX call to retrieve some results based on the dropdown value that was selected.

function fetchLines(){ $.ajax({ url: baseURL + "resources/ajax.php?node=fetchLines", type: 'GET', cache: false, data: { lineType: 'business' }, error: function(err) { alert(err.statusText); }, success: function(data) { console.log(data); } }); } 

In this AJAX file, I am trying to turn on my controller and then access the function inside it.

 <?php define('BASEPATH', "AJAX"); require_once('../application/controllers/Project.php'); switch($_REQUEST['node']){ case 'fetchLines': $objLines = new Project(); $objLines->fetchLines($_REQUEST['lineType']); break; } ?> 

My CI controller then has a private function that I try to call to get the data I need:

 private function fetchLines($lineType){ $lines = $this->project_model->fetchLines($lineType); return $lines; } 

My goal is for all of my AJAX calls to use an AJAX file or controller (if necessary). It must have access to the controller and return data.

With the current code above, I get the error: Class 'CI_Controller' not found in <b>C:\xampp\htdocs\blueprint\application\controllers \Project.php

Is there a better way to deal with such situations? I am not an OOP specialist, but some readings offer something in this direction.

+4
source share
3 answers

why don't you send this request instead of the controller method?

  function fetchLines(){ $.ajax({ url: baseURL + "controller-name/method-name", type: 'GET', cache: false, data: {lineType: 'business'}, error: function(err) { alert(err.statusText); }, success: function(data) { console.log(data); } }); } 

NOTE , and in the controller you can access these values ​​as

 function method-name(){ echo $this->input->get('lineType'); } 
+1
source

Let's say my ajax file is in the controllers folder And I want to reuse my controllers, I would do it like this:

 $this->load->library('../controllers/your_controller'); $this->your_controller->_some_method($data); 

Download the controller as a library and use it as a library. Hope this helps.

0
source

You should put code that listens for an AJAX call only in the controller function. How you try to do this is not good practice. If you want the method to be executed only if the request was an ieAJAX XHR request, use

if($this->input->is_ajax_request()){ //your code }else{ redirect(base_url()) }

0
source

All Articles