views:

783

answers:

2

I don't get what I'm doing wrong.

I'm trying to populate a form from a JSON string from the server and it doesn't work. I get nothing at all back. I examine the object and it's undefined. I've been beating my head against the wall for 3 days now. I need a simple example that works and I'll build from there.

Here's the simple example that I've been trying to use:

var messages = new Ext.data.JsonStore({
 url: '/user/' + user_id,
 method: 'GET',
 root: 'user',
 fields: [
          {name: 'user_id'},
          {name: 'first_name'}
  ],
  listeners: {
  load: messagesLoaded
 }
});

messages.load();

function messagesLoaded(messages) {
    console.log(messages);
}

Here's my JSON string:

{"success":"true","user":{"user_id":"2","first_name":"Test","last_name":"Test","email":null,"password":null,"city_id":"6379","birth_date":"2009-06-09","gender":"F","created_on":"2009-06-01 17:21:07","updated_on":"2009-06-14 17:20:14","active":"Y","cuisine_id":null}}

I really don't see what I'm doing wrong, but my JSON string isn't loading. Thanks!

+4  A: 

Ok so you're almost there, but one problem. The root ("user" in this case) has to be an array. Even if it's an array with only 1 object. Ext.data.JsonReader (the default reader for a Ext.data.JsonStore) only accepts an array of results.

So your javascript looks just fine, but the JSON object returned by the server needs to look more like this.

{
    "success":"true",
    "user": [{
        "user_id":"2",
        "first_name":"Test",
        "last_name":"Test",
        "email":null,
        "password":null,
        "city_id":"6379",
        "birth_date":"2009-06-09",
        "gender":"F",
        "created_on":"2009-06-01 17:21:07",
        "updated_on":"2009-06-14 17:20:14",
        "active":"Y",
        "cuisine_id":null
    }]
}
scott
Thanks - that was my problem. I changed the "user" tag to "data" and removed the root from my code and it worked. Slowly but surely I'm figuring this out.
jeffkolez
+2  A: 

One more thing, consoloe.logging your store object will produce something like [Object] in Firebug... not too useful. You should either console.dir it, or log your actual data instead.

One comment about loading your form, once you get past loading your JSON (even though this example does not show that). Make sure your form is actually rendered before trying to load it with data, e.g. if trying to use something like form.loadRecord. Otherwise you'll end up with an empty form and no errors.

bmoeskau
...something new every day. I’ve been gleefully using console.log for as long as firebug has let me... didn't even know console.dir was there... brilliant. Thanks!
OhkaBaka