19

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

7
  • 1
    You're not sending the form data => !empty($username) fails -=> PHP sends back an empty response => Unexpected end of JSON input Commented Sep 1, 2022 at 9:49
  • Whe I add the dataType: 'json' to my javascript. I become the following error: "[object Object]" is not valid JSON Commented Sep 1, 2022 at 9:51
  • 10
    @JonathanFuchs Because then data has already been parsed as JSON, so parsing an already parsed object will fail. Commented Sep 1, 2022 at 9:53
  • I add the data tag and the response is following: {"success":1} But the error: SyntaxError: "[object Object]" is not valid JSON Commented Sep 1, 2022 at 9:54
  • 1
    Useful tip: know the difference between JSON (a string) and a Javascript Object - specifically how they appear in the browser console when debugging. Then you can console.log(data) and you'll know immediately that it's already an object. Commented Sep 1, 2022 at 10:04

2 Answers 2

39

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);
Sign up to request clarification or add additional context in comments.

2 Comments

This worked for me. Content-Type of my Post request is: application/json console.log(JSON.parse(JSON.stringify(req.body)));
@user1579234 if you're going to write console.log(JSON.parse(JSON.stringify(req.body)));, then you could have written console.log(req.body); and got the same result. If you parse a JSON string, and then immediately turn it back into a string again, as your example does, then you're simply ending up back exactly where you started from. So in your case, req.body must be a JSON string when it arrives in your code. This answer is about what happens when jQuery automatically parses a JSON string into an object before it's passed to your code.
0

Try do it to avoid this error:

myFunction(data: string) {
  try {
    JSON.parse(data); 
    console.log(data);
  }
   catch (e) {
   console.log(e); 
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.