Home > database >  SyntaxError: "[object Object]" is not valid JSON
SyntaxError: "[object Object]" is not valid JSON

Time:09-02

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

My requestedt URL via 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 js:

$(() => {
    $('.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 the response from the php {"success":1} is not right? What is the problem?

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

CodePudding user response:

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);
  • Related