Some Sencha form JSON encode and POST examples

It’s hard to find good Sencha JSON encoding and form POST examples, so here’s a quick collection of JSON examples I found while working yesterday. I know that these examples work with Sencha ExtJS; they may also work with Sencha Touch.

JSON encode a JavaScript object

First, the following example comes from this page, and shows how to convert a JavaScript object to JSON in an AJAX request:

Ext.Ajax.request({
    url: '/saveData.php',
    success: function() { Ext.Msg.alert('Success'); },
    failure: function() { Ext.Msg.alert('Fail'); },
    jsonData: Ext.util.JSON.encode(dataObj)
});

As you can see, that example uses Ext.util.JSON.encode to JSON encode an object.

JSON encode a JavaScript dictionary with jsonData

Next, this example shows how to POST a dictionary of strings as JSON in a Ext.Ajax.request. Note the use of the jsonData key in this example:

Ext.Ajax.request({
  url : 'doSomething.htm',
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },                     
  params : { "test" : "testParam" },
  jsonData: {
      "username" : "admin",
      "emailId" : "admin@sivalabs.com"
  },
  success: function (response) {
      var jsonResp = Ext.util.JSON.decode(response.responseText);
      Ext.Msg.alert("Info","UserName from Server : "+jsonResp.username);
  },
  failure: function (response) {
      var jsonResp = Ext.util.JSON.decode(response.responseText);
      Ext.Msg.alert("Error",jsonResp.error);
  }
});

JSON encode Sencha form values

Lastly, this discussion includes a few Sencha JSON POST examples in a form submit process. The most important code for me yesterday was the following block, which shows how to easily JSON encode the form values/variables:

{
  xtype: 'button',
  text: 'Create',
  scope: this,
  formBind: true,
  handler: function(btn) {
      form.submit({
          method:'POST', 
          headers: {
              'Content-Type': 'application/json;charset=utf-8'
          },
          params: Ext.util.JSON.encode(form.getValues()),
          waitTitle:'Connecting', 
          waitMsg:'Creating...',
          success:function(data){             
          },
          failure:function(form, result){
          }
      });
  }
}

The key code in that example for me is this:

params: Ext.util.JSON.encode(form.getValues()),

Until I saw that code, I was handling my form variables manually. I know that was probably wrong, but I didn’t know the correct solution until I saw this code.

In summary, if you needed some Sencha form JSON POST examples, in particular those that show how to JSON encode form data, I hope these examples have been helpful.