Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error "SyntaxError: "[object Object]" is not valid JSON"

I have a problem with the following code. The console.log output is:

My requested URL via a JavaScript Ajax request is the "login.php":

 <?php include('init.php');
    use Login\LoginService;

    #include(__DIR__.'/Login/LoginService.php');

    global $pdo;
    session_start();

    $username = $_POST['username'];
    $pass = $_POST['password'];
    if (!empty($username)) {
        $test = new LoginService();
        $user = $test->getUsersLogin($username);
        if (!empty($user) && $user[0]['login'] == $username) {
            $json = json_encode(array("success" => 1));
            echo $json;
        } else {
            $json = json_encode(array("success" => 0));
            echo $json;
        }
    }
    ?>

My Ajax request via JavaScript:

$(() => {
    $('.login-form').on('submit', function (e) {
        e.preventDefault();

        $.ajax({
            type: "POST",
            dataType: "json",
            timeout: 500,
            url: '/src/login.php',
            data: $(this).serialize(),

            success: (data) => {
                try {
                    var jso = JSON.parse(data);
                    console.log(jso);
                } catch (e) {
                    console.log(e);
                    return false;
                }
            },
            error: (data) => {
                console.log(JSON.parse(data));
            }
        });
    });
});

Why is the response from the PHP {"success":1} not right? What is the problem?

SyntaxError: "[object Object]" is not valid JSON

like image 221
Jonathan Fuchs Avatar asked Dec 02 '25 23:12

Jonathan Fuchs


1 Answers

If you write dataType: "json" then jQuery will automatically parse your response as JSON before it comes to the "success" function. This is described in the jQuery $.ajax documentation.

Therefore, data is already an object. You cannot pass an object into JSON.parse() - it requires a string.

Instead of

var jso = JSON.parse(data); console.log(jso);

you can just write

console.log(data);
like image 176
ADyson Avatar answered Dec 04 '25 11:12

ADyson