jose
jose

Reputation: 1562

How to get data directly from json response ajax request

My app has a form populated via binding or the methods form.getForm().loadRecord ().

To this form are dynamically added two fields that I want to populate directly from the response of an Ext.Ajax.request.

What is the best way to get the data directly from json response ajax request?

Ext.Ajax.request({
  url: 'php/read',
  method: 'POST',
  params: {
    'myId': myId,
  },
  success: function (conn, response, options, eOpts) {

      var one = //get directly from request response (json) //????

  },
  failure: function (conn, response, options, eOpts) {
  }
 });

var one = //get directly from request response (json) //???
var two = ...

Ext.ComponentQuery.query('#fieldOne')[0].setValue(one);
Ext.ComponentQuery.query('#fieldTwo')[0].setValue(two);

.

//json 
 data:{
   one: "A",
   two: "B"
 }

EDITED

To get response data:

 success: function (response, options) {
     var resp = Ext.decode(response.responseText);
     //or
     var resp2 = response.responseText;
 }

With resp I get:

 Object
   success: Object
   data: Array[1]

With resp2 I get:

   {"success":{"success":true},"data":[{"one":"A","two":"B"}]}

It was supposed to access the data as follows:

resp.one
//or
resp2.one
//or
resp.data.one

However, it returns 'undefined'.

What's missing to get 'one' value?

Upvotes: 0

Views: 1038

Answers (1)

Jeremy Jackson
Jeremy Jackson

Reputation: 2257

You'll need to call a function once your success callback return some data. This is purely example and may not work exactly as you need, but it'll show you what I mean:

Ext.Ajax.request({
    url: 'php/read',
    method: 'POST',
    params: {
        'myId': myId,
    },
    success: function(conn, response, options, eOpts) {
        setFields(response);
    },
    failure: function(conn, response, options, eOpts) {}
});

function setFields(response) {
    Ext.ComponentQuery.query('#fieldOne')[0].setValue(response.one);
    Ext.ComponentQuery.query('#fieldTwo')[0].setValue(response.two);
}

Because you're waiting for your callback function to return, you won't be able to set your variables. So that's why the above needs to happen. You could also do it within the callback, but the function is cleaner.

Upvotes: 3

Related Questions