Check for Ajax request in CodeIgniter

Check for Ajax request in CodeIgniter

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Checking for Ajax Requests in CodeIgniter

The approach you are currently using relies on checking the HTTP_X_REQUESTED_WITH header against the string "XMLHttpRequest". While this works for basic jQuery calls, it is a fragile heuristic that breaks with modern frameworks like Axios or Fetch API, which often omit this header entirely. In CodeIgniter, relying on raw $_SERVER variables for access control logic creates a tight coupling between your application's security boundaries and outdated browser behaviors.

CodeIgniter provides built-in functionality to handle this scenario more robustly through its Request object. The framework automatically parses incoming headers and exposes them via the $request instance injected into controllers or accessible globally. Instead of defining a global constant in index.php, you should leverage the request method detection provided by the library.

You can check for an Ajax request within your controller logic using the is_ajax() method available on the request object. In CodeIgniter 4, this is accessed via $this->request->isAjax(). This method returns a boolean value indicating whether the request was initiated by JavaScript or a similar client-side technology.

public function index()
{
    if (!$this->request->isAjax()) {
        return redirect('home'); // Or show an error page
    }

    // Proceed with API logic
}

In CodeIgniter 3, the global $this->input object serves a similar purpose. The method is_ajax_request() allows you to verify the request type without manually parsing headers. This abstraction handles the nuances of different libraries and browsers, ensuring your application doesn't inadvertently block valid calls from modern JavaScript tools that don't set the legacy header.

However, relying solely on the presence of an Ajax marker is often a red flag for poor security architecture. The standard practice in web development is to build APIs that are secure regardless of the client type. If you restrict direct access via GET requests but allow POST, PUT, or DELETE operations without proper authentication, you leave your API vulnerable to Cross-Site Request Forgery (CSRF) and unauthorized data manipulation.

A more elegant solution involves shifting the focus from "blocking non-Ajax users" to "requiring valid sessions or tokens for all state-changing actions." If your application is a Single Page Application (SPA), you can configure routes to treat them as API endpoints. In CodeIgniter 4, this is often done by placing API controllers in a specific directory and using route filters or middleware to enforce authentication logic only on those paths.

// Example of applying a filter to specific API routes
$routes->group('api', ['filter' => 'auth'], function ($routes) {
    $routes->get('users', 'UserController::index');
});

Using filters or middleware ensures that the logic for identifying Ajax requests is decoupled from the core security policy. If a user attempts to access an API endpoint via a browser directly, the request will fail the authentication filter regardless of whether they are using fetch, jQuery, or a custom client. This eliminates the need to guess which header your users might send.

The trade-off with the is_ajax() method is that it creates a "magic door." It allows unauthenticated access if the request comes from JavaScript. This is dangerous because an attacker can craft a browser-based attack that mimics an Ajax call using simple forms or hidden inputs. Security should never depend on user-agent headers or request types; it must depend on tokens and sessions.

If you are migrating legacy logic where direct script access was explicitly forbidden, consider whether that restriction is actually necessary for the API layer. Modern frameworks encourage treating all traffic to an API endpoint as untrusted until proven otherwise via authentication headers like Authorization: Bearer <token>.

For developers looking for similar patterns in other ecosystems, the principle remains consistent: abstract away the transport details from the security logic. If you find yourself constantly tweaking header checks, it might be time to review your authentication middleware configuration. Resources like https://laravelcompany.com often discuss these architectural shifts, emphasizing that secure API design relies on state management and tokens rather than request headers.

Ultimately, CodeIgniter's isAjax() method is the correct tool for detecting the client type, but it should be part of a larger strategy where access control is enforced by authentication middleware, not by checking if the user is using JavaScript to make the call.

Our network