11

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jonathan Fuchs
  • 129
  • 1
  • 1
  • 7
  • 1
    You're not sending the form data => `!empty($username)` fails -=> PHP sends back an empty response => Unexpected end of JSON input –  Sep 01 '22 at 09:49
  • Whe I add the dataType: 'json' to my javascript. I become the following error: "[object Object]" is not valid JSON – Jonathan Fuchs Sep 01 '22 at 09:51
  • 8
    @JonathanFuchs Because then `data` has already been parsed as JSON, so parsing an already parsed object will fail. – Ivar Sep 01 '22 at 09:53
  • I add the data tag and the response is following: {"success":1} But the error: SyntaxError: "[object Object]" is not valid JSON – Jonathan Fuchs Sep 01 '22 at 09:54
  • Related: `error: (data) =>` - data will never be sent to the `error` handler as the error handler means something went wrong with the *request* itself - so `JSON.parse(data)` will always give an error. Check the documentation for the correct parameters: https://api.jquery.com/jquery.ajax/ – freedomn-m Sep 01 '22 at 10:02
  • 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. – freedomn-m Sep 01 '22 at 10:04
  • I was getting this error after I had upgraded jQuery to latest version 3.6. Later on, I found out that I had not upgraded `Microsoft jQuery Unobtrusive Ajax` nuget package as per this [answer](https://stackoverflow.com/a/15539422/465053). – RBT Sep 29 '22 at 08:57

2 Answers2

21

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);
ADyson
  • 57,178
  • 14
  • 51
  • 63
0

Try do it to avoid this error:

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