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:
The Yii::$app->request component provides methods for accessing request data.
$request = Yii::$app->request;if (Yii::$app->request->isGet) {
echo "This is a GET request";
}
if (Yii::$app->request->isPost) {
echo "This is a POST request";
}$id = Yii::$app->request->get('id'); // Example: ?id=10With default value:
$id = Yii::$app->request->get('id', 0); // Default value = 0$name = Yii::$app->request->post('name');$headers = Yii::$app->request->headers;
$userAgent = $headers->get('User-Agent');$cookie = Yii::$app->request->cookies->get('user_session');$file = UploadedFile::getInstanceByName('profile_picture');
$file->saveAs('uploads/' . $file->baseName . '.' . $file->extension);The Yii::$app->response component allows sending responses to the client.
Yii::$app->response->content = 'Hello, Dynamic Duniya!';Yii::$app->response->statusCode = 404;Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return ['message' => 'Success', 'status' => 200];return Yii::$app->response->sendFile('path/to/file.pdf');return Yii::$app->response->redirect(['site/index']);return Yii::$app->response->redirect(['site/index'], 301);When sending a JSON response from a standard Yii2 controller (not a RESTful API controller), it's essential to explicitly set the response format.
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;
}Yii::$app->response->format = Response::FORMAT_JSON; ensures the correct Content-Type (application/json) is sent.$.ajax({
url: '/site/ajax-example',
type: 'POST',
data: {name: 'Rahul'},
success: function(response) {
console.log(response);
}
});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');
}if (Yii::$app->request->isAjax) {
echo "This is an AJAX request";
}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.
Sign in to join the discussion and post comments.
Sign in