Akdora’s Blog

Programming, Oracle, Life, Fun

How to use Ext.Ajax.request with Response Text? February 6, 2009

If we want to query something via ajax and show a response on the screen, we can use Ext.Ajax.request class of ExtJS. It provides a simple way to make Ajax requests with maximum flexibility. We will set the action url and get a response from action. Then, we will show the response on the screen. Let’s do it.

Firstly, I am writing the JSP page:

<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<link rel="stylesheet" type="text/css" href="/xx/resources/extjs/css/ext-all.css">
<script type="text/javascript" src="/xx/resources/extjs/ext-base.js"></script>
<script type="text/javascript" src="/xx/resources/extjs/ext-all-debug.js"></script>
<script type="text/javascript">
Ext.onReady(function() {

 function fn_AKExt( message, title ){
   Ext.Msg.show({
      title: title,
      msg: message ,
      buttons: Ext.MessageBox.OK,
      icon: Ext.MessageBox.INFO
     });
 }
 function fn_submitForm(button,event){
   var f = Ext.getCmp('myFormPanel');
   if( f.getForm().isValid() == true)
   {
       var startDate = Ext.getCmp('startDate');
       var finishDate = Ext.getCmp('finishDate');
       Ext.Ajax.request({
         url : 'xxxxAction.do?MID=getReservableType',
                  method: 'POST',
                  params :{sd:startDate.value, fd:finishDate.value},
                  success: function ( result, request ) {
                      var jsonData = Ext.util.JSON.decode(result.responseText);
                      var resultMessage = jsonData.data.result;
                      fn_AKExt(resultMessage, 'Success');
               },
                  failure: function ( result, request ) {
                   var jsonData = Ext.util.JSON.decode(result.responseText);
                   var resultMessage = jsonData.data.result;
                   fn_AKExt(resultMessage, 'Error');
               }
       });
   }else{
    alert("Tüm alanları doldurmadınız!");
   }
   }
 var myFormPanel = new Ext.FormPanel({
        labelWidth: 180,
        id: 'myFormPanel',
        frame:true,
        title: 'Kampanya Tanım Formu',
        bodyStyle:'padding:5px 5px 0',
        width: 480,
        defaults: {width: 170},
        defaultType: 'textfield',
        bodyBorder: false,
        bodyStyle:'padding:5px 5px 0; border-width: 0px;',
        monitorValid:true,
  items: [{
           
            xtype:'fieldset',
            id : 'fieldset1',
            title: 'xxx',
            collapsible: false,
            autoHeight: true,
            autoWidth : true,
            defaults: {width: 230},
            defaultType: 'textfield',
            waitMsgTarget: true,
         waitMsg:'Loading',
         
           
         items: [
          new Ext.form.DateField({
                 fieldLabel: 'Start Date',
                 name: 'startDate',
                 format : 'd.m.Y',
                 readOnly :true
              }),
              new Ext.form.DateField({
                 fieldLabel: 'Finish Date',
                 name: 'finishDate',
                 format : 'd.m.Y',
                 readOnly :true
              })      
   ]
        }
       
        ],
        buttons: [{
            text: 'Kaydet',
            handler: fn_submitForm
        }],
        renderTo: 'content'
    });
});
</script> 
<table>
 <tr >
  <td  valign="top">
   <div name="content" id="content"></div>
  </td>
 </tr>
</table>

Let’s take a closer look important part of code. In ExtçAjax Method we have some parameters:

 url : ‘xxxxAction.do?MID=getReservableType’,  >> Our Action to call
 method: ‘POST’, >> Call method
 params :{sd:startDate.value, fd:finishDate.value}, >> Parameters!!

We have also response methods :

success: function ( result, request ) {
                      var jsonData = Ext.util.JSON.decode(result.responseText);
                      var resultMessage = jsonData.data.result;
                     fn_AKExt(resultMessage, ‘Success’);
               },
failure: function ( result, request ) {
                   var jsonData = Ext.util.JSON.decode(result.responseText);
                  var resultMessage = jsonData.data.result;
                  fn_AKExt(resultMessage, ‘Error’);

}

Then, we write our Action Class. Here, we get the parameters we sent from jsp class and set them a variable. Then, we do some business staff. I called an EJB and get a number result. So I will write the result on the screen as a alert with “fn_AKExt” function on the jsp page.

public class xxxxAction extends BaseAction {
 private xxxxxx po;
 public ActionForward getReservableType(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response) throws Exception {
  
  String startDate = (String)request.getAttribute("sd");
  String finishDate = (String)request.getAttribute("fd");
  
  if(startDate != null && startDate.compareTo("")!=0 && finishDate !=null && finishDate.compareTo("") != 0)
  {
   po = (xxxxxx) EJBUtil.getEJB("xxxxxxEJB");
   
   int result = po.getReservableNumber(startDate, finishDate); 
   String resultDesc = "";
   resultDesc = String.valueOf(result) + " campaign(s) reserved!!!";
   if(result < 0)
   {
    resultDesc = "An error occured!!";
   }
   String jsonStr = "{\"success\":true,\"data\":{\"result\":\"" + resultDesc + "\"}}";
   response.setContentType("text/html;charset=iso-8859-9");
   response.getWriter().write(jsonStr);
  }
  return mapping.findForward("");
 }
}

 

Advertisement
 

9 Responses to “How to use Ext.Ajax.request with Response Text?”

  1. […] How to use Ext.Ajax.request with Response Text? […]

  2. ekolhoca Says:

    Thanks good article

  3. I have some problem with the form, look my mistake:

    f is undefined
    [Break on this error] if( f.getForm().isValid() == true)\r\n

    • akdora Says:

      Hi Wilfredo,
      I had changed some of code before I post here.

      I think you should put the “function fn_submitForm” function below the grid definition. In a sequential code compiling the
      “var f = Ext.getCmp(‘myFormPanel’);”
      have not created yet.

      Thx for the error

  4. C.Shamis Says:

    Sorry, I don’t understand. What’s all the black-magic going on with the Ext.JSON.decode(result.responseText) Where’s the “.responseText” coming from?

    What about resultMessage = jsonData.data.result; Where’s .data.result being defined? Is that the “.result” of the “data” node you created in the JSON string being returned by your action?

    Isn’t the “reponse” the verbatum text returned by the action? Also, what’s going on with the {{success:true},{data:{….}}} format in the JSON you’re crafting.

    I assume the “{success:true} is to satisfy the action component of the ajax call, but what goes in the “data” part? Is that the “payload” that I’m actually interested in? Is it “rooted” under a the “data” node in your JSON string?

    This is a great example showing how to wire up the AJAX call, and that’s a huge help. But, without knowing how to dig the payload information out of the JSON that my action produces, it’s somewhat incomplete…

    -C.

    • akdora Says:

      Hi Shamis,
      I wrote the code a long time ago. I rarely remember it 🙂

      The “.responseText” should be a standart feature .. I am not sure. I should try it again. You can also google it.

      The “.data.result” is defined in the xxxxAction class. You can see the red and green colors.

      Actually I had not been used the “{success:true}” part of JSON string in jsp page. I use there “result” string of the “data” node of JSON String as “JSON->data->result” string. I also have “JSON->success”, but i did no use it.

      Thx

  5. Thanks, you helped me a lot to find the way back again.

  6. Here is a simple example to understand to use Ext.Ajax. http://extjstutorial.info/extjs-4-tutorial-easy-ajax-using-extjs-4-php-mysql/66 . This blog post using ExtJS version 4


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s