背景
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
がなくなり、データもフロント側に出た。