简体   繁体   中英

SyntaxError: Unexpected token < in JSON at position 0 ajax php

I'm building a website using PHP & Ajax. I can't fetch data. I constantly get "SyntaxError: Unexpected token < in JSON at position 0 " However, the data is sent to my database successfully and there're no errors in the network.

Ajax file:

document.getElementById("btnSendPrivateMessage").addEventListener("click", function (e) {
    e.preventDefault();

    let chatId = this.dataset.chatid;
    let text = document.querySelector('#privateMessageText').value;

    console.log(chatId);
    console.log(text);


    //sent to DB
    let formData = new FormData();

    formData.append("text_message", text);
    formData.append("chat_id", chatId);

    fetch("ajax/saveMessage.php", {
        method: "POST",
        body: formData
    })
    .then(response => response.json())
    .then(result => {
        console.log("Success:", result);
    })
    .catch(error => {
        console.error("Error:", error);
    });
});

PHP file with json_encode

<?php 
require("../classes/Db.class.php");
require("../classes/ChatPrivateMessage.class.php");
require("../datetime.php");
session_start();  

if(!empty($_POST)){
    header("Content-type: application/json");

    $m = new ChatPrivateMessage();

    $m->setChatId($_POST['chat_id']);
    $m->setText($_POST['text_message']);
    $m->setUser1($_SESSION['user_id']);
    $m->setDate(getTime());

    $textM = htmlspecialchars($m->getText()) ;


    $m->saveMessage();

    $response = [
        "status" => "success",
        "body" => $textM,
        "message" => "something"
    ];

    header("Content-type:application/json"); 

    echo json_encode($response);
};  
?>

It seems like server doesn't respond with JSON but with HTML (maybe it responds with HTML page describing the error occurred). Check what the backend response is exactly.

for friends who want to check up-to-date, if there is any HTML code information on the page where you are processing the code, it reads the information sent from ajax but returns an error. Therefore, there should not be any HTML code on the processed page. Otherwise you will get an error. Note that the page is purely php codes. This way my problem was fixed. It is very simple and requires attention.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM