I have a question about the following code. The output of console.log is:
The URL I requested via a JavaScript Ajax request was "login.php":
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 JavaScript Ajax request:
$(() => { $('.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 PHP's response of {"success":1}
incorrect? what is the problem?
SyntaxError: "[object Object]" is not valid JSON
Try this to avoid this error:
If you write
dataType: "json"
, then jQuery will automatically parse your response into JSON before entering the "success" function. This isdescribed in detail
in jQuery's$.ajaxdocumentation.Therefore,
data
is already an object. You cannot pass an object toJSON.parse()
- it expects a string.So, no need
You can write directly