Blog Archive

ExtJs 4 Ajax Request and Response example using Java Servlet and JSON

AJAX stand for Asynchronous JavaScript and XML. AJAX is not a technology in itself, it is a way of developing Web applications that combines: HTML or XHTML, Cascading Style Sheets, JavaScript, The Document Object Model, XML, XSLT, and the most importantly XMLHttpRequest object.

When these technologies are combined in the AJAX model, web applications are able to make quick, incremental updates to the user interface without reloading the entire browser page making sites faster. Also AJAX is asynchronous, so you can run processes in background that can update the UI without any user interaction.

Although X in AJAX stands for XML, JSON is used more than XML nowadays because of its many advantages such as being lighter and a part of JavaScript. Both JSON and XML are used for packaging information in AJAX model. This example of AJAX request uses JSON, ExtJs JavaScript framework and Java Servlet on the backend. Here we have created a simple Login form that will take a userId and password and then make an AJAX request to validate the request.

ExtJs 4 Ajax JSON Request and Response example using Java Servlet
ExtJs 4 Ajax JSON Request and Response example using Java Servlet
ExtJs 4 Ajax JSON Request and Response example using Java Servlet

Our application HTML file - index.html

    <title>ExtJs 4 Ajax Request and Response Example</title>

    <link rel="stylesheet" type="text/css" href="extjs/resources/css/ext-all.css">
    <script type="text/javascript" src="extjs/ext-all-debug.js"></script>
    <script type="text/javascript" src="app.js"></script>


Our application Javascript file - apps.js

    enabled: true 

    name: 'MyAjaxApp',

    appFolder: 'app',
    controllers: [

    launch: function() {
        Ext.create('Ext.container.Viewport', {
            items: [
                    xtype: 'ajaxRequestForm',

Javascript source for Login form - AjaxRequestForm.js

Ext.define('MyAjaxApp.view.AjaxRequestForm', {
    extend: 'Ext.form.Panel',
    alias : 'widget.ajaxRequestForm',
    width: 500,
    frame: true,
    title: 'ExtJs Ajax Request Example',
    bodyPadding: '10 10 0',

    defaults: {
        anchor: '100%',
        allowBlank: false,
        msgTarget: 'side',
        labelWidth: 75

    items: [{
        xtype: 'textfield',
        name: 'userId',
        fieldLabel: 'User Id'
        xtype: 'textfield',
        name: 'password',
        fieldLabel: 'Password',
        inputType: 'password',

    buttons: [{
        text: 'Submit',
        action: 'login'
        text: 'Reset Form',
        handler: function() {

Javascript source for ExtJs controller - AjaxExample.js

Ext.define('MyAjaxApp.controller.AjaxExample', {
            extend : '',

            //define the views
            views : ['AjaxRequestForm'],

            //special method that is called when your application boots
            init : function() {
                //control function makes it easy to listen to events on 
                //your view classes and take some action with a handler function
                            //when the viewport is rendered
                            'viewport > panel' : {
                                render : this.onPanelRendered
                            //when you click Submit button
                            'ajaxRequestForm button[action=login]' : {
                                click : this.onLoginRequest   

            onPanelRendered : function() {
                //just a console log to show when the panel is rendered
                console.log('The panel was rendered');
            onLoginRequest : function(button) {
                //just a console log to show when the Login Ajax request starts
                console.log('Login Ajax Request in progress');
                var form = button.up('form').getForm();
                   //create an AJAX request
                        url : 'Login',
                        params : {
                            loginData: Ext.encode(form.getValues())
                        scope : this,
                        //method to call when the request is successful
                        success : this.onLoginSuccess,
                        //method to call when the request is a failure
                        failure : this.onLoginFailure
            onLoginFailure : function(err) {
                //Alert the user about communication error
                Ext.MessageBox.alert('Error occured during Login', 'Please try again!');

            onLoginSuccess : function(response, opts) {
                //Received response from the server
                response = Ext.decode(response.responseText);
                    Ext.MessageBox.alert('Successful Login', response.message);
                else {
                    Ext.MessageBox.alert('Login failed', response.message);

Ext.Ajax.request parameters

  • url
    • The URL to which to send the request, or a function to call which returns a URL string.
  • params
    • An object containing properties which are used as parameters to the request, a url encoded string or a function to call to get either.
  • method
    • The HTTP method to use for the request. Defaults to the configured method, or if no method was configured, "GET" if no parameters are being sent, and "POST" if parameters are being sent.
  • success
    • The function to be called upon success of the request. The following parameters are passed to this function
      • response: The XMLHttpRequest object containing the response data.
      • option: The parameter to the request call.
  • failure
    • The function to be called upon success of the request. The following parameters are passed to this function
      • response: The XMLHttpRequest object containing the response data.
      • options: The parameter to the request call.

ExtJs 4 Ajax JSON Request and Response example using Java Servlet
ExtJs 4 Ajax JSON Request and Response example using Java Servlet

Java Object source for our user Information -

package com.as400samplecode;

public class UserInfo {
    String userId = null;
    String password = null;
    public String getUserId() {
        return userId;
    public void setUserId(String userId) {
        this.userId = userId;
    public String getPassword() {
        return password;
    public void setPassword(String password) {
        this.password = password;


Java Servlet source for validating user Information -

package com.as400samplecode;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class Login extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public Login() {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String loginData = request.getParameter("loginData");
        Gson gson = new Gson();
        UserInfo userInfo = gson.fromJson(loginData, UserInfo.class);
        String userId = userInfo.getUserId();
        String password = userInfo.getPassword();

        PrintWriter out = response.getWriter();
        response.setHeader("Cache-control", "no-cache, no-store");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "-1");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST,GET");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        response.setHeader("Access-Control-Max-Age", "86400");

        JsonObject myObj = new JsonObject();

        //nothing was sent   
        if(userId == null || password == null){
            myObj.addProperty("success", false);
            myObj.addProperty("message", "Please send userId and Password!");
        else {
            if(userId.trim().equals("ajax") && password.trim().equals("request")){
                myObj.addProperty("success", true);
                myObj.addProperty("message", "Welcome to");
            else {
                myObj.addProperty("success", false);
                myObj.addProperty("message", "Looks like you forgot your login infomartion");


  1. Simply superb... Good Explanation and thanks for sharing your knowledge.. Good work..

  2. You know any work arround from using a form submit instead ajax request?

  3. good, for dummies!!!

  4. Thanks a lot . for such an good explanation and the example

  5. Very good explanation. Thanks for the tutorial.

  6. m getting error in this line
    myObj.addProperty("success", true);
    error-The method addProperty(String, String) in the type JsonObject is not applicable for the arguments (String, boolean)

  7. Good one Bro keep the great wok goin..!!!!!!!1

  8. Im getting "NetworkError: 404 Not Found - http://localhost:8080/exttest/Login"

    1. You have a config problem. It's not finding your files

  9. When should I use the alias or the ext.define object in the controller to reference a button or something?

  10. good a post
    if i fetch from DB 100 records, and now i want to paginate it
    how i can do it? please help me

  11. in your controller line 34, button is not defined

  12. Is it possible in "Javascript source for ExtJs controller - AjaxExample.js" to display backend throwable in the failure field?