Praveen Singh

AJAX Framework using JQuery: An Object Oriented approch

AJAX FRAMEWORK USING JQUERY: AN OBJECT ORIENTED APPROACH

Content

  1. Introduction
  2. Very short theory on AJAX.
  3. Overview of application "Book Search", will build this application.
  4. Overview of UI Framework.
  5. A basic AJAX call using our UI framework.
  6. A advance AJAX call using our UI framework.
  7. Appendix A: Java and JEE server side code(Only for Java developers)
  8. Appendix B: Video walk through with YouTube video(Make sure you use this as much you can, with my experience a video illustration of application with working demo is best way to explain things).


step by step video tutorial


Introduction


Recently i worked in a website development, where one of the task was to build a UI framework.
I was told that we will be using AJAX heavily and almost all the call via AJAX/JSON call.

With my experience in AJAX with JQuery, i thought, after some google search, i will be ready with UI Fraework.
But even with hours of search all i was getting, 'Hello world with AJAX' app with help of JQuery.
I end up realizing that there is shortage of a UI framework or industry level AJAX code with JQuery on world wide web.
So i decided to put code which i used in my project, online, by converting it to very simple application.
So i will start with putting basic UI framework in place and then enhance it to advance form


Very short theory on AJAX.

Someone put few technicall words, Asynchronous Javascript and xml, together and we know it as  AJAX.
But this is not what is important, important is almost every new and modern  website use this today.

So how AJAX work......?

Look at the below image.

  • A simple AJAX call always be Asynchronus, though synchronus call is possible.
  • Request can be handled without browser refresh, and some time, without user knowledge.
  • Server provide response in text, html snnipets, xml, csv, json etc. All you need to do is put proper parsing logic in javascript in client/Browser side.
  • Though not mandatory but JSON(Javascript Object Notation) is prefered way of communication on AJAX due to it's various advantages.




Overview of application "Book Search", will build this application.

 We will try to build a very simple example of book serch.
This application does following job.
  1. Serach book by id and display details on UI.
  2. 'Book' a book by its id (Available in Section 5 and 6 only).

Overview of UI Framework

    Below is the flow diagram of the UI Framework which we will build in this blog

Major Componets of UI Framework

1. Browser/HTML page
Browser or HTML page take care of generating events.
It is place you click on button or submit a form, etc.

2. EventService
This layer can be considered as the Service layer, which is the first place to handle events, generated by Browser or HTML page.

3. AjaxMgr
This is the class which encapsulate all the api responsible to do AJAX call to server.

4. Server Component.
Server componet could be any server side code which can deliver the json response, it could be Java, PHP, .Net, etc
Since, in this blog, our main aim is to create UI Framework, will will not be focusing on server side component much.
An server side componet, which can deliver json like below is good enough for me.
 


Reason for choice of above data

We should try to get atleast below type in data packet.

1. String: bookName, description (notice, it appear with quotes)

2. int. id (notice, it appear without quotes)

3. float: price.(notice, it appear without quotes)

4. Date  dateOfPublication (notice, it appear with quotes)


A basic AJAX call using our UI framework.

In this section will try to build the application to do the AJAX call with basic functionality of UI Framework.
If you are a expert UI/Javscript developer, you might find few component not in best shape.
Though things are right and good for mid level complexity, you might want to suggest something better.
I would just request here to hold your thoughts for Advance part of this tutorial, where we will try to improve this application further.

To start this application, lets follow the structure of the application first.
Application has below structure.
























I devloped this application on Eclipse IDE and in format of a Java EE project.
If you are looking for a PHP or any other example.
Just club, static and view folder and do something extra to make it work(which i dont know as i am from java background only :( )
Create folder like above and start dumping code like below

/view/simpleAjaxCall.html
This file holds the html to trigger the events on UI(for more detail explanation, follow youtube video on Appendix B)



        <html>
<head>
<script src="../static/jquery/jquery-1.9.0.js"></script>
<script src="../static/js/simple/eventService.js"></script>
<script src="../static/js/simple/framework.js"></script>
<style type="text/css">
body {
  background-color: #EFEFC6
}

#centerPane {
  width: 960px;
  border: 1px grey solid;
  margin: 0px auto;
  min-height: 400px;
  background-color: white;
}

#topHeading {
  font-size: 40px;
  font-weight: bold;
  margin: 0px 5px;
}

#bookDetailsDiv {
  margin: 5px 5px 5px 40px;
}
</style>
</head>
<body>
<div id="centerPane">
<label id="topHeading">BookSearch - Simple</label>
 <label id="bookId">Provide Book Id:</label>
  
<input id="bookIdTextBox" type="text" value="1234" />
<input id="bookIdSubmit" onclick="searchBook()" type="button" value="Submit" />
<br />
<div id="bookDetailsDiv">
</div>
</div>
</body>
</html>





/static/js/simple/eventService.js
Hold the business events and call UI Framework(for more detail explanation, follow youtube video on Appendix B)

function searchBook() {

  var bookId = $("#bookIdTextBox").val();
  var ajaxMgr = new AjaxMgr();
  ajaxMgr.setUrl("/OOAjaxDemo/BookController");
  ajaxMgr.appendData("bookId", bookId);
  ajaxMgr.doGet();
}

function searchBookSuccess(data) {
  console.log('in searchBookSuccess');
  if (data.id != undefined) {
    var breakMarkup = "";
    var bookData = "";
    bookData += "id:" + data.id + breakMarkup;
    bookData += "Book Name :" + data.bookName + breakMarkup;
    bookData += "Author Name:" + data.authorName + breakMarkup;
    bookData += "price:" + data.price + breakMarkup;
    bookData += "Date Of Publication:" + data.dateOfPublication
        + breakMarkup;
    bookData += "Description:" + data.description + breakMarkup;
    bookData += "";
    $("#bookDetailsDiv").html(bookData);
  } else {
    $("#bookDetailsDiv").html("Sorry no data in found for this id");
  }
}




/static/js/simple/framework.js
 Hold the UI framework code(for more detail explanation, follow youtube video on Appendix B)


function AjaxMgr() {
  var url = '';
  var data = '';
  var dataType = 'json';
  var timeout = 600000;
  var type = 'post';

  this.setUrl = function(urlVal) {
    url = urlVal;
  };
  this.appendData = function(keyVal, valueVal) {
    data += "&" + keyVal + "=" + valueVal;
  };
  this.setTimeOut = function(timeoutVal) {
    timeout = timeoutVal;
  };
  this.setType = function(typeVal) {
    type = typeVal;
  };
  this.doGet = function() {
    type = "GET";
    doAjax();
  };

  this.doPost = function() {
    type = "POST";
    doAjax();
  };
  var doAjax = function() {
    console.log("in doAjax");
    $.ajax({
      type : type,
      dataType : dataType,
      url : url,
      timeout : timeout,
      data : data,
      success : function(data, textStatus, xhr) {
        console.log("In success");
        console.log("Data: " + data);
        searchBookSuccess(data);
      },
      error : function(data, textStatus, xhr) {
        console.log("data: " + data);
        console.log("textStatus: " + textStatus);
      }
    });
  };
}



With above code are in place, if you run the URL
http://localhost:8080/OOAjaxDemo/view/simpleAjaxCall.html

You should see the below page



If you click with value '1234' and submit, you will see the below screen



If you try to provide some other value = 123


 A advance AJAX call using our UI framework.

/view/complexAjaxCall.html
Hold the html of complex part of this demo
(for more detail explanation, follow youtube video on Appendix B)
 



<html>
<head>
<script src="../static/jquery/jquery-1.9.0.js"></script>
<script src="../static/js/complex/eventService.js"></script>
<script src="../static/js/complex/framework.js"></script>
<style type="text/css">
body {
  background-color: #EFEFC6
}

#centerPane {
  width: 960px;
  border: 1px grey solid;
  margin: 0px auto;
  min-height: 400px;
  background-color: white;
}

#topHeading {
  font-size: 40px;
  font-weight: bold;
  margin: 0px 5px;
}

#bookDetailsDiv {
  margin: 5px 5px 5px 40px;
}
</style>
</head>
<body>
<div id="centerPane">
<label id="topHeading">BookSearch.com</label>
<br />
<form action="/OOAjaxDemo/BookController" id="bookForm">
<label id="bookId">Provide Book Id:</label>
<input id="bookIdTextBox" name="bookId" type="text" value="1234" />
<input id="bookIdSubmit" type="submit" value="Submit" />
</form>
<div id="bookDetailsDiv">
</div>
</div>
</head>
</html>


/static/js/complex/eventService.js

    var searchBook = {
  init : function(formEle) {
    console.log('in init');
    var url =  $(formEle).attr("action");
    var formId =  $(formEle).attr("id");
    console.log('formId: ' + formId);
    console.log('url: ' + url);
    var ajaxMgr = new AjaxMgr();
    ajaxMgr.setUrl(url);
    ajaxMgr.addFormData(formId);
    ajaxMgr.setSuccessFunction(this.success);
    ajaxMgr.setErrorFunction(this.error);
    ajaxMgr.doGet();

  },
  success : function(data) {
    console.log('in searchBook.success');
    if (data.id != undefined) {
      var breakMarkup = "";
      var bookData = "";
      bookData += "id:" + data.id + breakMarkup;
      bookData += "Book Name :" + data.bookName + breakMarkup;
      bookData += "Author Name:" + data.authorName + breakMarkup;
      bookData += "price:" + data.price + breakMarkup;
      bookData += "Date Of Publication:" + data.dateOfPublication
          + breakMarkup;
      bookData += "Description:" + data.description + breakMarkup;
      bookData += "";
      $("#bookDetailsDiv").html(bookData);
    } else {
      $("#bookDetailsDiv").html("Sorry no data in found for this id");
    }
  },
  error : function(data) {
    console.log('in searchBook.error');
    $("#bookDetailsDiv").html("Sorry something bad happen!");
  }
};

$(document).ready(function() {
  $("#bookForm").on("submit",function(e){
    e.preventDefault();
    searchBook.init(this);
    
  });
});



/static/js/complex/framework.js
Hold the framework code for complex part

function AjaxMgr() {
  var url = '';
  var data = '';
  var successFunction = null;
  var errorFunction = null;
  var dataType = 'json';
  var timeout = 600000;
  var type = 'post';
  this.setUrl = function(urlVal) {
    url = urlVal;
  };
  this.setSuccessFunction = function(successFunctionVal) {
    successFunction = successFunctionVal;
  };
  this.addFormData = function(formIdVal) {
     data += "&" + $('#' + formIdVal).serialize();
  };
  this.appendData = function(keyVal, valueVal) {
    data += "&" + keyVal + "=" + valueVal;
  };
  this.setErrorFunction = function(errorFunctionVal) {
    errorFunction = errorFunctionVal;
  };
  this.setTimeOut = function(timeoutVal) {
    timeout = timeoutVal;
  };
  this.setFormData = function(formIdVal) {
    formId = formIdVal;
    data += "&" + $('#' + formIdVal).serialize();
  };
  this.setType = function(typeVal) {
    type = typeVal;
  };
  this.setFormId = function(formIdVal) {
    formId = formIdVal;
  };
  this.doGet = function()
  {
    type = "GET";
    doAjax();
  };
  
  this.doPost = function()
  {
    type = "POST";
    doAjax();
  };
  var doAjax = function() {
    $.ajax({
      type : type,
      dataType : dataType,
      url : url,
      timeout : timeout,
      data : data,
      beforeSend: function()
      {
        
        console.log("Do something before AJAX call");
      },
      success : function(data, textStatus, xhr) {
        console.log("In success");
        console.log("Data: " + data);
        if(successFunction != null)
        {
                    if ((successFunction != null)) {
                        successFunction(data);
                    }
        }
      },
      error : function(data, textStatus, xhr) {
        console.log("data: " + data);
        console.log("textStatus: " + textStatus);
      },
            complete: function () {
              console.log("Do something Agter AJAX call");
            }
    });
  };
  
  var doLoadingAnimation = function()
  {
    type = "POST";
    doAjax();
  };
} 

    

 Appendix A: Java and JEE server side code(Only for Java developers)

Below is the java code package and details.
It will give you a better idea, where to put what
































Below are the important class with there full path,
(for more detail explanation, follow youtube video on Appendix B)


/WEB-INF/web.xml


<web-app id="WebApp_ID" version="2.5" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name>OOAjaxDemo</display-name>
  <servlet>
    <description></description>
    <display-name>BookController</display-name>
    <servlet-name>BookController</servlet-name>
    <servlet-class>com.icodingclub.controller.BookController</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>BookController</servlet-name>
    <url-pattern>/BookController</url-pattern>
  </servlet-mapping>
</web-app>



src/com/icodingclub/controller/BookController.java



package com.icodingclub.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.icodingclub.entity.Book;
import com.icodingclub.service.BookService;
import com.icodingclub.util.ControllerUtil;

@SuppressWarnings("serial")
public class BookController extends HttpServlet
{
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException
  {
    String bookId = request.getParameter("bookId");
    System.out.println("bookId: " + bookId);
    Book book = BookService.getBook(bookId);
    String jsonData = ControllerUtil.toJson(book);
    ControllerUtil.writeOnResponse(response, jsonData);

  }
}




src/com/icodingclub/entity/Book.java



package com.icodingclub.entity;

import java.util.Date;


public class Book
{
  private int id;
  
  private String bookName;
  
  private String authorName;
  
  private float price;
  
  private Date dateOfPublication;
  
  private String description;


  
  public int getId()
  {
    return id;
  }

  public String getBookName()
  {
    return bookName;
  }

  public String getAuthorName()
  {
    return authorName;
  }

  public String getDescription()
  {
    return description;
  }

  public float getPrice()
  {
    return price;
  }

  public void setPrice(float price)
  {
    this.price = price;
  }
  

  public Date getDateOfPublication()
  {
    return dateOfPublication;
  }

  public Book(int id, String bookName, String authorName, float price, Date dateOfPublication,
      String description)
  {
    super();
    this.id = id;
    this.bookName = bookName;
    this.authorName = authorName;
    this.price = price;
    this.dateOfPublication = dateOfPublication;
    this.description = description;
  }

  @Override
  public String toString()
  {
    return "Book [id=" + id + ", bookName=" + bookName + ", authorName=" + authorName
        + ", price=" + price + ", dateOfPublication=" + dateOfPublication
        + ", description=" + description + "]";
  }

  
  

}




src/com/icodingclub/service/BookService.java



package com.icodingclub.service;

import java.util.Calendar;

import com.icodingclub.entity.Book;

public class BookService
{
  public static Book getBook(String id)
  {
    Book book = null;
    if (id.equals("1234"))
    {
      Calendar cal = Calendar.getInstance();
      cal.set(13, 02, 1984);
      book = new Book(1234, "iCodingClib Journal", "Praveen Singh",(float)500.45, cal.getTime(), "This journal include all the blog content from iCodingClub blog");
    }
    return book;
  }
}



src/com/icodingclub/util/ControllerUtil.java


package com.icodingclub.util;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

public class ControllerUtil
{
  public static String toJson(Object object)
  {
    if(object == null)
    {
      object = new Object();
    }
    JSONObject obj = new JSONObject(object);
    obj.remove("class");
    return obj.toString();
  }

  public static void writeOnResponse(HttpServletResponse response, String jsonData)
  {
    response.setContentType("application/json");
    PrintWriter out = null;
    try
    {
      out = response.getWriter();
    }
    catch (IOException e)
    {
      System.out.println("SOME EXCEPTION - PLEASE HANDLE BY YORSELF");
      e.printStackTrace();
    }
    out.write(jsonData);
    out.flush();
  }
}




src/com/icodingclub/test/Test.java



package com.icodingclub.test;

import com.icodingclub.entity.Book;
import com.icodingclub.service.BookService;
import com.icodingclub.util.ControllerUtil;

public class Test
{
  public static void main(String[] args)
  {
    Book book = BookService.getBook("1234");
    String jsonData = ControllerUtil.toJson(book);
    System.out.println(jsonData);
  }
}

1 comment: