1

I want to do a web project using Yii2, and I want to return a JSON to AJAX. I have used json_encode() and Yii::$app->response->format = Response::FORMAT_JSON;, but it still doesn't work.

Here is my action:

public function actionAbout(){
  Yii::$app->response->format = Response::FORMAT_JSON;
  return json_encode(["test"=> 1]);
}

Here is my AJAX:

$.ajax({
  type: "POST",
  // dataType: 'json',
  data: {
    'user': 'A'
  },
  url: "?site/about",
  contentType: "application/json",
  success: function(data) {
    console.log(typeof(data));
    console.log(data)
  },
  error: function (data) {
    console.log(data);
  },
});

But it returns this:

<!DOCTYPE html>....

still a html. How to solve it?

Jap Mul
  • 17,398
  • 5
  • 55
  • 66
Bastian Fei
  • 23
  • 2
  • 5
  • Works fine for me. Although you shouldn't `json_encode` the array yourself when setting the response type to `FORMAT_JSON`. What's the complete response? – Jap Mul Nov 15 '17 at 14:57

1 Answers1

0

Instead of using

return json_encode(["test"=> 1]);

shouldn't you be echoing it like this

echo json_encode(["test"=> 1]);

plus if you ARE setting the Yii::$app->response->format to FORMAT_JSON then you do not need to encode the array to JSON just return the array.

return ['test'=>1];
Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68