Error: SyntaxError: Unexpected non-whitespace character after JSON at position 52 (line 1 column 53)

I’m experiencing a JSON parsing error with the message:

‘SyntaxError: Unexpected non-whitespace character after JSON at
position 52 (line 1 column 53)’.

Could you help me understand what might be causing this? I suspect there might be some unexpected characters or output before the JSON response.

this is my code:

function bayar() {
    const tagihan = <?php echo json_encode($tagihan_belum_dibayar[0] ?? null) ?>;
    
    if (!tagihan) {
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'Tidak ada tagihan yang perlu dibayar'
        });
        return;
    }

    Swal.fire({
        title: 'Memproses Pembayaran',
        text: 'Mohon tunggu...',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });

    fetch('./process_payment.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },
        body: JSON.stringify({
            total_tagihan: parseFloat(tagihan.total_tagihan)
        })
    })
    .then(response => {
        // Pastikan response dalam format JSON
        const contentType = response.headers.get('content-type');
        if (!contentType || !contentType.includes('application/json')) {
            throw new Error('Bukan respon JSON');
        }
        return response.json();
    })
    .then(data => {
        Swal.close();
        if (data.status === 'success') {
            $('#orderIdInput').val(data.order_id);
            $('#jumlahPembayaranInput').val(new Intl.NumberFormat('id-ID', {
                style: 'currency',
                currency: 'IDR'
            }).format(data.total_bayar));
            
            $('#modalPembayaranBaru').modal('hide');
            $('#modalUploadBukti').modal('show');
        } else {
            throw new Error(data.message || 'Terjadi kesalahan');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        Swal.fire({
            icon: 'error',
            title: 'Gagal',
            text: error.message || 'Terjadi kesalahan dalam pemrosesan'
        });
    });
}

// Update form submission handler
document.getElementById('uploadBuktiForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    
    Swal.fire({
        title: 'Mengupload Bukti Pembayaran',
        text: 'Mohon tunggu...',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });

    fetch('', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        Swal.fire({
            icon: 'success',
            title: 'Berhasil',
            text: 'Bukti pembayaran berhasil diupload'
        }).then(() => {
            window.location.reload();
        });
    })
    .catch(error => {
        Swal.fire({
            icon: 'error',
            title: 'Gagal',
            text: 'Gagal mengupload bukti pembayaran'
        });
    });
});

Can you advise on how to troubleshoot this issue and ensure a clean JSON response?

“I tried to send a JSON request from the client-side using JavaScript’s fetch API to a PHP backend. I was expecting a clean JSON response that would be parsed without any errors.

Specifically:

  • I sent a POST request to process a payment

  • The server-side PHP script was supposed to generate a JSON response

  • Instead, I received this parsing error at position 52

What I expected was a response like:

{
  "status": "success",
  "order_id": "123456",
  "total_bayar": 500000
}

But the error suggests something unexpected is being sent before or within the JSON data.

I’ve already tried:

  • Checking server-side PHP for any extra output

  • Using ob_clean() to clear output buffer

  • Verifying Content-Type headers

  • Ensuring no error messages are printed

Could you help me identify what might be causing these unexpected characters?