1

Sorry about this nth version of object grabbing, but I just don't see it.

I am returning a JSON object from a db to my Javascript, and I see the returned object (below) just fine in the console. But the moment I attempt to put a child in the console I get "undefined". I should be able to see result.bills, or result["bills"] and just to be sure I've tried result[0].bills, etc. all of which are undefined. This seems so basic but I can't see why I can't make this work.

My PHP (after db stuff):

if ($result) { 
    $rows = array();
    while($r = mysqli_fetch_assoc($result)) {
        $rows[bills] = $r;
    }  
    echo json_encode($rows);
} else {
    echo "Unknown Error";   
}
//all done

My AJAX:

$.ajax({
    type: 'get',
    url: 'GetBills.php',
    success: function(result) {
        var thebills = result.bills;
        console.log(thebills);          
    },
    error: function(xhr, desc, err) {
        console.log(xhr);
        console.log("Details: " + desc + "\nError:" + err);
    }
});

and I get back:

{
    "bills": {
        "ID": "3",
        "State": "MD",
        "Title": "Maryland Android Project Act (S.1196 H.2057)",
        "HouseNum": "H 2057",
        "SenateNum": "",
        "Session": "189th"
    }
}
6
  • For one thing,$rows[bills] will at least get you a PHP warning, since bills is neither a variable nor a string. Effectively, this statement is repeatedly storing $r into the same array element.
    – Aldo
    Dec 7, 2015 at 21:03
  • How do you know you are getting back {"bills":{"ID":"3","State":"MD","Title":"Maryland Android Project Act (S.1196 H.2057)","HouseNum":"H 2057","SenateNum":"","Session":"189th"}} ? From the network tab or just by console.log()?
    – benjaminz
    Dec 7, 2015 at 21:05
  • @benjaminz: that's the xhr log. The undefined is the console. Dec 7, 2015 at 21:07
  • To clarify at bit, the xhr is the whole thing, but I am trying to grab the first child object, which I named "bills" myself in the php for clarity. Dec 7, 2015 at 21:09
  • @ColdSharper what did you get when you do console.log(result); after the ajax call?
    – benjaminz
    Dec 7, 2015 at 21:09

3 Answers 3

5

You're getting undefined because jQuery doesn't know that it's actually receiving JSON back. It is detected and automatically parsed if you send JSON headers with your php file, OR if you set the dataType to 'json'.

So, currently you're accessing a string:

var result = '{"bills":{"ID":"3","State":"MD","Title":"Maryland Android Project Act (S.1196 H.2057)","HouseNum":"H 2057","SenateNum":"","Session":"189th"}}'

BUT you're attempting to access STRING functions (specifically bills which is undefined).

If you choose to not change the dataType or add headers, you could also do result = JSON.parse(result) which would also give you the same thing.

Doing one of the three above solutions will give you the object you're looking for, and access its children:

//Javascript
result = JSON.parse(result);

//In Console
Object {bills: Object}
bills: 
   ObjectHouseNum: "H 2057"
   ID: "3"
   SenateNum: ""
   Session: "189th"
   State: "MD"
   Title: "Maryland Android Project Act (S.1196 H.2057)"
__proto__: Object
__proto__: Object
1
  • 1
    great explanation. Thank you. I knew this, but I didn't know it. Dec 7, 2015 at 21:20
3

add dataType to your ajax request object: ...

type: 'get',
url: 'GetBills.php',
dataType: 'json',

...

1
  • That helped! I didn't think you had to explicitly do that if you return json. Dec 7, 2015 at 21:12
1

You can either force the content type to be JSON in your AJAX call, or even better, set the correct content type in your PHP and let jQuery detect it automatically. Imagine accessing your data from another tool different from jQuery, e.g. a mobile app or some REST-tool. If you set your Content Type properly, most tools/languages will detect it automatically and you don't have to parse it manually over and over again.

// Set the content type correctly
header('Content-Type: application/json');

if ($result) {
    $rows = array();

    while ($r = mysqli_fetch_assoc($result))
    {
        $rows[] = $r; // Notice how to append the row to the array
    }

    http_response_code(200); // PHP >= 5.4
    echo json_encode([
        'success' => true,
        'bills' => $rows
    ]); 
}
else {
    http_response_code(500); // Your status code here
    echo json_encode([
        'success' => false,
        'message' => 'Something went wrong',
    ]);
}

And your JavaScript:

$.ajax({
    type: 'get',
    url: 'GetBills.php',
    success: function(result) {
        var thebills = result.bills;
        console.log(thebills);
    },
    error: function(response) {
        console.log('Error', response.message);
    }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.