Sunday, March 12, 2017

Sencha Touch - XHR2

Sencha touch provides XHR2 confiuration to work with Ajax and Ajax2 development.
XHR2 is xmlHttpRequest level2 , which used to request data from server. For any web application data resides at the server and once the page is loaded the data should be accessed from server with the help of Ajax requests.

XHR2 in Sencha touch provides the progress bar feature which shows user the amount of data transferred for particular request.
XHR2 is the newly added so we need to check if the browser supports it or not.
Function to check whether browser supports XHR2 is:
if (Ext.feature.has.XHR2) {
    // Here we can write functionality to work if browser supports XHR2 
}  
We can even check if the progressive upload with XHR2 supported by browser or not as:
if (Ext.feature.has.XHRUploadProgress) {
        // Here we can write functionality to work if browser supports progressive uploads
}
Various new XHR2 features are included in Sencha touch.
Features Description
XHR2: true This is used to enable and disable XHR2 functionality in the application.
Ext.field.File New file field is added to give more cality about the type of field.
Ext.field.FileInput This to provide FileInput.
Ext.progressIndicator This is to provide exact percentage of data transferred in terms of progress bar.
xtype: fileinput To create instance of fileInput class.
xtype: filefield To create instance of file class.
responseType : value This parameter allows various types of responses as text, document, blob etc.
Below we will see some examples to send simple ajax request with and without parameter and uploading files using ajax.

Simple Ajax request without parameters - Success

<!DOCTYPE html>
<html>
   <head>
      <link href="https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/sencha-touch.css" rel="stylesheet" />
      <script type="text/javascript" src="https://cdn.sencha.com/touch/sencha-touch-2.4.2/sencha-touch-all.js"></script>
      <script type="text/javascript">
         Ext.setup({
            requires: [
               'Ext.Panel',
               'Ext.Button',
               'Ext.form.Panel'
            ],
            onReady: function() {
               var request = {
                  url: 'https://www.tutorialspoint.com/sencha_touch/index.htm',
                  method: 'POST',
                  xhr2: true,
                  success: function(response) {
                     Ext.Msg.alert('Ajax call successful');
                  },
                  failure: function(response) {
                     Ext.Msg.alert('Ajax call failed');
                  }
               };
               Ext.Viewport.add({
                  xtype:"panel",
                  layout:"vbox",
                  fullscreen:true,
                  items: [
                     {
                        xtype:"button",
                        text: "Ajax",
                        ui: 'confirm',
                        handler: function(){
                           Ext.Ajax.request(request);
                        }
                     }
                  ]
               });
            }
         });
      </script>
   </head>
   <body>
   </body>
</html>
The above example shows the success ajax call as the URL mentioned is correct. In this example we are not passing any parameter its just a simple ajax request which hits the URL mentioned.
If you are using chrome browser in the developer tool navigate to the network section you can see the request which is getting sent and the response which we get.

Simple Ajax request without parameters- failure

<!DOCTYPE html>
<html>
   <head>
      <link href="https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/sencha-touch.css" rel="stylesheet" />
      <script type="text/javascript" src="https://cdn.sencha.com/touch/sencha-touch-2.4.2/sencha-touch-all.js"></script>
      <script type="text/javascript">
         Ext.setup({
            requires: [
               'Ext.Panel',
               'Ext.Button',
               'Ext.form.Panel'
            ],
            onReady: function() {
               var request = {
                  url: 'https://www.tutorialspoint.com/sencha_touch/indexx.htm',
                  method: 'POST',
                  xhr2: true,
                  success: function(response) {
                     Ext.Msg.alert('Ajax call successful');
                  },
                  failure: function(response) {
                     Ext.Msg.alert('Ajax call failed');
                  }
               };
               Ext.Viewport.add({
                  xtype:"panel",
                  layout:"vbox",
                  fullscreen:true,
                  items: [
                     {
                        xtype:"button",
                        text: "Ajax",
                        ui: 'confirm',
                        handler: function(){
                           Ext.Ajax.request(request);
                        }
                     }
                  ]
               });
            }
         });
      </script>
   </head>
   <body>
   </body>
</html>
In the above example just to show how ajax failure works we have mentioned the wrong URL compare this and previous example you will find the difference.

Sending parameters in Ajax request

<!DOCTYPE html>
<html>
   <head>
      <link href="https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/sencha-touch.css" rel="stylesheet" />
      <script type="text/javascript" src="https://cdn.sencha.com/touch/sencha-touch-2.4.2/sencha-touch-all.js"></script>
      <script type="text/javascript">
         Ext.setup({
            requires: [
               'Ext.Panel',
               'Ext.Button',
               'Ext.form.Panel'
            ],

            onReady: function() {
               var formData = new FormData();
               formData.append("firstName", "Hi");
               formData.append("lastName", "Reader");

               // Request will be sent as part of the payload instead of standard post data
               var request = {
                  url: 'https://www.tutorialspoint.com/sencha_touch/sencha_json.php',
                  method: 'POST',
                  xhr2: true,
                  data: formData,
                  success: function(response) {
                     var out = Ext.getCmp("output");
                     response = Ext.JSON.decode(response.responseText, true);
                     Ext.Msg.alert(response.message);
                  },
                  failure: function(response) {
                     var out = Ext.getCmp("output");
                     Ext.Msg.alert('Ajax failed!');
                  }
               };

               Ext.Viewport.add({
                  xtype:"panel",
                  layout:"vbox",
                  fullscreen:true,
                  items: [
                     {
                        xtype:"button",
                        text: "Ajax",
                        ui: 'confirm',
                        handler: function(){
                           Ext.Ajax.request(request);
                        }
                     }
                  ]
               });
            }
         });      
      </script>
   </head>
   <body>
   </body>
</html>
In this example we are passing parameters with the ajax using data property of ajax call.

Uploading files using Ajax

<!DOCTYPE html>
<html>
   <head>
      <link href="https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/sencha-touch.css" rel="stylesheet" />
      <script type="text/javascript" src="https://cdn.sencha.com/touch/sencha-touch-2.4.2/sencha-touch-all.js"></script>
      <script type="text/javascript">
         Ext.setup({
            requires: [
               'Ext.Panel',
               'Ext.MessageBox',
               'Ext.Button',
               'Ext.ProgressIndicator',
               'Ext.form.Panel',
               'Ext.field.FileInput'
            ],

            onReady: function() {
               var progressIndicator = Ext.create("Ext.ProgressIndicator", {
                  loadingText: "Uploading: {percent}%"
               });

               var request = {
                  url: 'https://www.tutorialspoint.com/sencha_touch/sencha_json.php',
                  method: 'POST',
                  xhr2: true,
                  progress:progressIndicator,
                  success: function(response) {
                     Ext.Msg.alert('File uploaded successfully.');
                  },
                  failure: function(response) {
                     Ext.Msg.alert('File upload failed.');
                  }
               };

               Ext.Viewport.add(progressIndicator);
               Ext.Viewport.add({
                  xtype:"panel",
                  layout:"vbox",
                  fullscreen:true,
                  items: [
                     {
                        xtype:"fileinput",
                        accept:"image/jpeg"
                     },
                     {
                        xtype:"button",
                        text: "Upload",
                        ui: 'confirm',
                        handler: function(){
                           var input = Ext.Viewport.down("fileinput").input;
                           var files = input.dom.files;
                           if (files.length) {
                              request.binaryData = files[0];
                              Ext.Ajax.request(request);
                           }else {
                              Ext.Msg.alert("Please Select a JPG");
                           }
                        }
                     }
                  ]
               });
            }
         });
      </script>
   </head>
   <body>
   </body>
</html>
This example shows how to upload data using ajax call. In this example we are using progress bar indicator to show the progress while uploading file.

1 comment:

  1. I have read this whole blog and it is an amazing blog who are developers and dealing daily with the new challenges. Thank You for sharing such a valuable, informative and useful thoughts for users in your blog.

    Hire Sencha Touch Developer
    Sencha Touch Development company
    Sencha Touch Development company usa

    ReplyDelete