Understanding Yii2 Request & Response Handling

Introduction

Yii2 provides a robust request and response handling mechanism, allowing developers to process HTTP requests and generate responses efficiently. The Request and Response components help in managing form submissions, handling AJAX calls, retrieving request parameters, and sending JSON or file responses.

In this tutorial, we will cover:

  1. Yii2 Request Component
  2. Handling GET and POST Requests
  3. Managing Request Data (Headers, Cookies, Files)
  4. Yii2 Response Component
  5. Sending JSON & File Responses
  6. Redirects & Custom Responses
  7. Sending JSON Response in Standard Controller
  8. Handling AJAX Requests in Yii2

1. Yii2 Request Component

The Yii::$app->request component provides methods for accessing request data.

Accessing Request Component

$request = Yii::$app->request;

2. Handling GET and POST Requests

Checking Request Type

if (Yii::$app->request->isGet) {
    echo "This is a GET request";
}

if (Yii::$app->request->isPost) {
    echo "This is a POST request";
}

Retrieving GET Parameters

$id = Yii::$app->request->get('id'); // Example: ?id=10

With default value:

$id = Yii::$app->request->get('id', 0); // Default value = 0

Retrieving POST Data

$name = Yii::$app->request->post('name');

3. Managing Request Data

Reading Headers

$headers = Yii::$app->request->headers;
$userAgent = $headers->get('User-Agent');

Handling Cookies

$cookie = Yii::$app->request->cookies->get('user_session');

Handling File Uploads

$file = UploadedFile::getInstanceByName('profile_picture');
$file->saveAs('uploads/' . $file->baseName . '.' . $file->extension);

4. Yii2 Response Component

The Yii::$app->response component allows sending responses to the client.

Setting Response Content

Yii::$app->response->content = 'Hello, Dynamic Duniya!';

Setting Response Status Code

Yii::$app->response->statusCode = 404;

5. Sending JSON & File Responses

Sending JSON Response

Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return ['message' => 'Success', 'status' => 200];

Sending File Response

return Yii::$app->response->sendFile('path/to/file.pdf');

6. Redirects & Custom Responses

Redirecting to Another Page

return Yii::$app->response->redirect(['site/index']);

Redirecting with Status Code

return Yii::$app->response->redirect(['site/index'], 301);

7. Sending JSON Response in Standard Controller

When sending a JSON response from a standard Yii2 controller (not a RESTful API controller), it's essential to explicitly set the response format.

Example: Returning JSON from a Controller Action

public function actionApi()
{
    $this->message = 'API Detail';

    $this->custom_response['detail'] = $this->message;

    $response = Yii::$app->response;
    $response->format = \yii\web\Response::FORMAT_JSON;
    $response->data = $this->custom_response;

    return $this->custom_response;
}

Why Set Response Format Manually?

  • By default, Yii2 controllers return HTML responses.
  • Setting Yii::$app->response->format = Response::FORMAT_JSON; ensures the correct Content-Type (application/json) is sent.
  • Useful for AJAX requests or API endpoints in non-RESTful controllers.

8. Handling AJAX Requests in Yii2

Sending AJAX Request (Frontend – JavaScript Example)

$.ajax({
    url: '/site/ajax-example',
    type: 'POST',
    data: {name: 'Rahul'},
    success: function(response) {
        console.log(response);
    }
});

Handling AJAX in Yii2 Controller

public function actionAjaxExample()
{
    if (Yii::$app->request->isAjax) {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return ['message' => 'Hello from Yii2!', 'status' => 200];
    }
    throw new BadRequestHttpException('Invalid request');
}

Checking AJAX Request in Yii2

if (Yii::$app->request->isAjax) {
    echo "This is an AJAX request";
}

Conclusion

Yii2 provides a flexible and powerful way to handle HTTP requests and responses. We explored how to retrieve GET/POST data, manage headers and cookies, send JSON responses, handle redirects, and process AJAX requests.

In the next tutorial, we will dive into Working with Yii2 Components & Helpers.