0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【PHP】parsererror SyntaxError: Unexpected end of JSON inputというエラーが出た

Posted at

背景
DBで保存したデータをフロント側で表示させたいが、
データはフロント側にうまく出てこないし、下記のエラーが出た。
parsererror SyntaxError: Unexpected end of JSON input

そもそもバック側からのレスポンスが届いた?と思って、functionを簡素化してテストしてみた。
フロント側:

$.ajax({
            url: "https://example.com/example/function/function.php",
            type: "POST",
            data: data,
            dataType: "json",
            success: function(response) {
                if (response.success) {
                    console.log(response.message);
                } else {
                    console.log(response.message);
                }
            },
            error: function(xhr, status, error) {
                console.log("AJAXエラー: ", xhr, status, error);
            }
        });

バック側:

header('Content-Type: application/json'); //レスポンスをJSONとして送信
function example(){
    echo json_encode(['success' => true, 'message' => 'ok']);
}

parsererror SyntaxError: Unexpected end of JSON inputが出た。

parsererror SyntaxError: Unexpected end of JSON input というエラーが出る理由は、サーバーから返ってくるレスポンスが JSON 形式になっていない、または空になっている可能性が高い。

エラーの原因
example()の出力の前に余計な出力がある
もしexample()を定義しているファイルや、それを呼び出すPHPファイルに空白、改行、エラーメッセージ、HTMLタグなどが含まれていると、出力が純粋な JSON ではなくなる。

解決策
最初にob_start()、最後にob_end_clean()を追加し、意図しない出力を防ぐ。

function example(){
    ob_start(); //出力バッファリングを開始
    echo json_encode(['success' => true, 'message' => 'ok']);
    ob_end_flush(); //バッファをフラッシュして送信
    exit();
}

parsererror SyntaxError: Unexpected end of JSON inputがなくなり、データもフロント側に出た。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?