search

Home  >  Q&A  >  body text

Title rewritten to: Error: "SyntaxError: """ is not a legal JSON format"

<p>I have a question about the following code. The output of <em>console.log</em> is: </p> <p>The URL I requested via a JavaScript Ajax request was "login.php": </p> <pre class="brush:php;toolbar:false;"><?php include('init.php'); use LoginLoginService; #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; } } ?></pre> <p>My JavaScript Ajax request:</p> <pre class="brush:php;toolbar:false;">$(() => { $('.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)); } }); }); });</pre> <p>Why is PHP's response of <code>{"success":1}</code> incorrect? what is the problem? </p> <blockquote> <p>SyntaxError: "[object Object]" is not valid JSON</p> </blockquote><p><br /></p>
P粉716228245P粉716228245458 days ago476

reply all(2)I'll reply

  • P粉738248522

    P粉7382485222023-08-23 11:56:34

    Try this to avoid this error:

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

    reply
    0
  • P粉505450505

    P粉5054505052023-08-23 11:42:19

    If you write dataType: "json", then jQuery will automatically parse your response into JSON before entering the "success" function. This is described in detail in jQuery's $.ajax documentation.

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

    So, no need

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

    You can write directly

    console.log(data);

    reply
    0
  • Cancelreply