Ajax + Controller Action in Yii2

Ajax + Controller Action in Yii2

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

Stefan Bogdanescu

Founder & Senior Architect

Debugging AJAX Calls in Yii2: The Form Data Trap

When integrating asynchronous requests into a Yii2 application, developers often encounter silent failures where the browser executes the JavaScript but never reaches the server-side controller action. This typically stems from a mismatch between what the client sends and how the framework interprets incoming data. In your specific scenario, the debugger indicates that no code runs on the server, which points directly to a configuration issue regarding form submissions rather than a syntax error in your AJAX handler.

The root cause lies in how Yii2 handles POST requests by default. When you submit a standard HTML <form> tag with the method="post" attribute, Yii automatically renders a hidden input field named _csrf. This mechanism is essential for preventing Cross-Site Request Forgery (CSRF) attacks, a critical security feature enabled in modern web frameworks. However, when your AJAX call attempts to mimic this behavior by sending data via jQuery's .ajax() method without explicitly including the CSRF token, Yii detects the missing token and rejects the request immediately.

In your views/index.php file, you are constructing the AJAX payload using:

data: {searchname: $("#searchname").val() , searchby:$("#searchby").val()}

This code correctly grabs the values from your input fields. However, it fails to include the hidden CSRF token that Yii expects. When $_POST['_csrf'] is absent in the request payload, Yii's security filter triggers a response that usually results in a 400 Bad Request or an empty response, effectively stopping your controller action from executing any logic beyond the initial validation check.

To resolve this, you must extract the CSRF token generated by Yii and append it to your AJAX data object. You can retrieve this token using yii\web\View::csrfMetaTag() or by accessing the meta tag directly in JavaScript if the view has already rendered it. A robust approach involves adding the token to the jQuery request:

var csrfToken = $('meta[name="csrf-token"]').attr('content');
$.ajax({
    url: Yii::$app->request.baseUrl + '/supermarkets/sample',
    type: 'post',
    data: {
        searchname: $("#searchname").val(), 
        searchby: $("#searchby").val(),
        _csrf: csrfToken
    },
    success: function (data) {
        alert(data);
    }
});

Alternatively, if you are rendering the view within a layout that includes Yii::$app->view->registerCsrfMetaTags(), the meta tag will automatically be injected into the <head> section. Ensuring this registration step is present in your layout is a prerequisite for the AJAX call to succeed. Without it, or without explicitly passing the token in the data payload, Yii will consistently block the request to protect against forgery.

Another potential pitfall involves the controller action itself. While your actionSample method currently only echoes "ok", ensure that the route /supermarkets/sample is correctly registered in your application's URL manager or module configuration. If the route is not defined, Yii will return a 404 Not Found error before the action logic even runs. Additionally, verify that your controller class extends yii\web\Controller and that the method name matches the route exactly (case-insensitive in most configurations, but exact match is recommended for clarity).

By aligning the client-side data submission with Yii's security requirements and ensuring the routing configuration is correct, your AJAX interaction will function as intended. This pattern of explicitly handling CSRF tokens is a standard requirement when moving from traditional form submissions to asynchronous interactions in PHP frameworks like Yii2 or Laravel.

Our network