I’ve used an Ajax call to look up a single record from a database, the response comes back and JSON.parse doesn’t work ("Unexpected identifier "object"") but I also get undefined when I try to access any of the values in it as an object.
Ajax call is:
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'php/mannoteslookup.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true,
success: function(data) {
console.log(data);
JSON.parse(data);
var name = data.lastname;
console.log(name);
$('#notes-modal-title').append(name);
},
error: function(error) {
console.log(error);
}
})
The json is returned from this php snippet:
$sql = "SELECT lastname, journal, progress_notes FROM myrecords WHERE id=" . $id;
$result = $conn->query($sql);
$dbdata = [];
while ($row = $result->fetch_assoc()) {
$dbdata[] = $row;
}
echo json_encode($dbdata);
The following is what’s returned:
[{"lastname":"Smalls","journal":"Nature Medicine","progress_notes":"2023-10-19 - Form notification receivedrn"}]
I’m still fairly new to this, but I’ve tried adding a header specifying json in the php, which seems to removes the quotes around the keys, but doesn’t change anything. I must be missing something, would greatly appreciate any advice/assistance.
3
Answers
Use as per below. data coming as Array having multiple objects
var name = data[0].lastname;
As @jaromanda X said, you’re not using parsed data but trying to access from the json string.
Following should work.
Btw, in 2023 using jQuery!! seems like you’re in wrong path. if you need suggestion then I’d like to say learn basic JS with good care then learn something like React, Vue or Svelte.
JSON.parse
is not required here because you specifieddataType : 'json'
. You’re not actually using it anyway as you’re not assigning the output from it. Sodata
is already a JavaScript array, not a JSON string.data
is an array because of this code in your PHP, which puts all results (if any) into an array.If (as I suspect from your query) you only expect one result from the query, you could simply use
Either way in your JS you need to check for a query which returns no results which you can do using optional chaining e.g.
Note that by using form data directly in your query (
$id
) you are vulnerable to SQL injection. I recommend reading this Q&A to see what that’s about and how to make your code safe.