Check for Ajax Request in CodeIgniter

Check for Ajax Request in CodeIgniter:

The CodeIgniter Input Class Provides lots of  helper functions to deal with user inputs , security etc.this class is initialized automatically by the system so there is no need to do it manually.

I always recommend you to use this class instead using PHP Core Input Variables while dealing with forms and requests.

To check Ajax Request in CodeIgniter, we will use codeIgniter Output Class Method class is_ajax_request() , this function checks to see if the HTTP_X_REQUESTED_WITH server header has been set, if set response will be true otherwise false means it will returns a boolean response.

 

we can use

 $this->input->is_ajax_request()

from the input class:

if (!$this->input->is_ajax_request()) {
     exit('No direct script access allowed');
}

As, CodeIgniter Library::

is_ajax_request()

Returns:TRUE if it is an Ajax request, FALSE if not
Return type:bool

Checks to see if the HTTP_X_REQUESTED_WITH server header has been set, and returns boolean TRUE if it is or FALSE if not.

 

 

Source:
https://www.codeigniter.com/user_guide/libraries/input.html

Undefined property $db in Codeigniter

Severity: Notice Message: Undefined property: CI::$db in codeigniter 3.16

Stack of codes

Are you facing any notice saying Undefined property: Home::$db or something like this in your Codeigniter application? The reason behind the error Undefined property $db in Codeigniter arises because you didn’t load database library in your controller/method to use any function of it.

This error also produces another Fatal error: Call to a member function on a non-object in your code.

Fix to Undefined property $db

To fix this error you should first include database library form Codeigniter in your controller/model or using Auto-load feature. Since database library is used at multiple places in your application so it would be better to load database library automatically when your system runs.

So open your application >  config > autoload.php file and replace

$autoload['libraries'] = array(); 

here, add Database library, LIKE,

$autoload['libraries'] = array('database');.

Or

alternatively you can call the following line in your controller construct/model or function if you are using database at only one or two places:

$this->load->database();