skip to Main Content

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


  1. Use as per below. data coming as Array having multiple objects

    var name = data[0].lastname;

    Login or Signup to reply.
  2. As @jaromanda X said, you’re not using parsed data but trying to access from the json string.
    Following should work.

     $.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); // this is string
    
            const dataObj = JSON.parse(data); // here is the change, using the parsed object
            var name = dataObj[0].lastname; // "dataObj[0]" because dataObj is an array according to your payload.
            console.log(name);
            $('#notes-modal-title').append(name);
        },
        error: function(error) {
            console.log(error);
        }
    })
    

    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.

    Login or Signup to reply.
  3. JSON.parse is not required here because you specified dataType : 'json'. You’re not actually using it anyway as you’re not assigning the output from it. So data 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.

    $dbdata = [];
    while ($row = $result->fetch_assoc()) {
        $dbdata[] = $row;
    }
    

    If (as I suspect from your query) you only expect one result from the query, you could simply use

    $dbdata = $result->fetch_assoc();
    

    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.

    // array
    name = data[0]?.lastname ?? 'Not found';
    // result
    name = data?.lastname ?? 'Not found';
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search