Cordova Android Application with Jquery Ajax request example that returns JSON

In this tutorial, let us see the steps to develop cordova android application that makes ajax request to  a web service or servlet that returns JSON array data using JQuery. If you are new to cordova app development then go through my earlier tutorial how to develop hello world app in Apache Cordova. For developing restful web service, you can visit my earlier tutorial building web service in java.   In this example, we will create an cordova android app having two radio buttons (Veg and Non Veg) and display menu items in a drop down list  based on the radio button selection.

Now let us see the steps to develop the application

This application has two parts (Part 1 and 2)

1. In Part 1, we  will be developing Mobile app using Cordova. This app will have two radio buttons. and one drop-down list component to display recipe menu items. On clicking the radio button will call the servlet that returns JSON data array.

2. In Part 2, we will develop a separate Dynamic web project having  servlet & DAO code for  returning JSON data array.

Before developing the app, you have to install and configure Apache cordova. You can visit my earlier tutorial for installing and configuring Apache Cordova in windows machine.

Technologies used

Apache Cordova 5.1.1
Java 1.8
JQuery Mobile 1.4.5
Eclipse Luna Service Release 2 (4.4.2)
Android 5.1.1


Part 1: (Creating Cordova Android Project)
1. Create a new cordova project (CordovaJQueryExample). Run the below command to create the project template.

F:\Cordova\Demo> cordova create CordovaJQueryExample net.javaonline.cordova.example.jquery CordovaJQueryExample

Once the project is created, you can see the config.xml file and other folders inside the directory CordovaJQueryExample as given in the below image. The config.xml, index.html and other files under www are common to all platforms. When the platform is added, these files are copied to that platform.

dir structure1


2. Add android platform for the cordova project

Change to the folder CordovaJQueryExample and give the below command

F:\Cordova\Demo\CordovaJQueryExample>cordova platform add android

Now You can find android folder inside the platforms folder. Each platform will have own copy of www folder under assets folder.

3. Add the Cordova project (android)  to eclipse

File -> Import -> Existing Android Code into WorkSpace

import cordova project to eclipse

Select the root directory as given below


and change the project name as CordovaJQueryExample and  finish . Now two projects are imported

  1. CordovaJQueryExample

2. CordovaLib which contains cordovalib.jar

Please compile to re-create the same jar.

Now add the folder www (which is common to all platforms) to the project CordovaJQueryExample.  You can see the following project structure.

Project Structure of Cordova Project:

cordova jquery project dir1cordova jquery project dir2

As per your requirement, you can add or change the files under www folder (shown in the above image) which is common to all platforms so that the changes/addition is copied to each platforms when you build the project.

4. Now let us develop the Cordova Jquery project. We are changing the following files to design our project.


The default index.html is modified to have the components of radio buttons and drop down list (select) as given in the below image.

cordova jquery output

This index file uses the following libraries


The complete index.html file is given below

<!DOCTYPE html>

        Customize this file as per requirement
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport"
	content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">

<link rel="stylesheet"
	href="" />
<script src=""></script>
<title>ABC Hotel</title>

		<div data-role="page" id="index">
			<div data-theme="a" data-role="header">
				<h3>ABC Hotel Menu List</h3>


			<div data-role="content">
				Select Veg or Non-Veg :
				<fieldset data-role="controlgroup" data-type="horizontal"
					data-mini="true" style="text-align: center" id="custom-fieldset">
					<input id="radio1" name="mnu" value="V" type="radio" /> <label
						for="radio1"> Veg </label> <input id="radio2" name="mnu"
						value="NV" type="radio" /> <label for="radio2"> Non Veg </label>

			<div data-role="fieldcontain">
				<label for="menu_list">Choose your favourite dish :</label> <select
					name="menu_list" id="menu_listId" data-native-menu="false">

			<div id="selectdId"></div>


	<!-- <script type="text/javascript" src="cordova.js"></script> -->
	<script type="text/javascript" src="js/index.js"></script>

5. Change the index.js file to use ajax for calling the servlet (getMenuList) that returns json array (dishes list) based on the selection of radio button (Veg/Non Veg). Include this index.js in the index.html. The complete index.js file given below.

//default index.html page is Modified 

var app = {
	// Application Constructor
	initialize : function() {
	// Bind Event Listeners
	// Bind any events that are required on startup. Common events are:
	// 'load', 'deviceready', 'offline', and 'online'.
	bindEvents : function() {
		$(document).ready(function() {
			$('input:radio[name=mnu]').change(function() {
				if (this.value == 'V') {
				} else if (this.value == 'NV') {


		$(document).ready(function() {
			$("#menu_listId").change(function() {
				var str = $("#menu_listId option:selected").text();

				$("#selectdId").text("You selected " + str);

		document.addEventListener('deviceready', this.onDeviceReady, false);
	// deviceready Event Handler
	// The scope of 'this' is the event. In order to call the 'receivedEvent'
	// function, we must explicitly call 'app.receivedEvent(...);'
	onDeviceReady : function() {
	// Update DOM on a Received Event
	receivedEvent : function(id) {
		var parentElement = document.getElementById(id);
		var listeningElement = parentElement.querySelector('.listening');
		var receivedElement = parentElement.querySelector('.received');

		listeningElement.setAttribute('style', 'display:none;');
		receivedElement.setAttribute('style', 'display:block;');

		console.log('Received Event: ' + id);


// parsing json data received from the server.

function menuListJsonDataParse(json) {

	var c = 0;

	var mylist = $("select#menu_listId");
	var tempOpt;

	$.each(json, function(key, value) {

		tempOpt = '<option value="' + key + '">' + value + '</option>';



// Calling the servlet that returns json data through ajax.
// we are using data type jsonp which supports cross domain url. if your servlet
// is deployed in the local server, then use local server/ client ip address
// instead of localhost.

function getMenuList(menuType) {


		type : "GET",
		url : ""
				+ menuType,
		dataType : 'jsonp',
		jsonpCallback : 'menuListJsonDataParse', // the function to call
		error : function() {
			alert("Errr is occured");

If you have developed any web service that returns JSON array and want to use that service, then replace the above servlet url mentioned in the function getMenuList in the index.js file with your web service url.

In the index.js, the function menuListJsonDataParse parses the JSON array and each item in the array is added to the drop down list box. Bind the change event of radio buttons and drop down list which are required on on start up.

Part 2: (Creating Dynamic Web Project)

6. Please ensure the you have created and started JavaOnlineWeb project with the servlet (getMenuList) in the same server or any other.

Dynamic Web Project Structure:


The servlet and DAO is given below




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

 * Servlet implementation class GetDetails
public class GetDetails extends HttpServlet {
	private static final long serialVersionUID = 1L;

	 * @see HttpServlet#HttpServlet()
	public GetDetails() {
		// TODO Auto-generated constructor stub

	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {


		response.setHeader("Cache-Control", "no-cache");

		// get the PrintWriter object to write the html page
		PrintWriter out = response.getWriter();

		String menuType = request.getParameter("menuType");

		String jsonData = "";

		try {

			JSONDao menuList = new JSONDao();

			try {
				jsonData = menuList.getMenuItems(menuType);
			} catch (Exception e) {
				// TODO Auto-generated catch block



		} finally {


	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub


import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JSONDao {

	public String getMenuItems(String menuType) throws JSONException {

		JSONObject details = new JSONObject();

		// Write DAO code to load dishes list and price from database put in the
		// JSON object (details). Here I have not written DAO code. I have just put 
		// static list in the JSON object
		// details.put("id", "name"+"--"+"price");

		if (menuType.equals("V")) {

			details.put("1", "Veg Thali -- Rs. 120");
			details.put("2", "Idli 2Pcs  -- Rs. 50");
			details.put("3", "Dosa -- Rs. 90");
			details.put("4", "Sambar Vada 2Pcs -- Rs. 50");

		else if (menuType.equals("NV")) {

			details.put("1", "Chicken Biriyani -- Rs. 175");
			details.put("2", "Mutton Biriyani -- Rs. 200");
			details.put("3", "Egg Biriyani -- Rs. 120");
			details.put("4", "Fish Curry with Rice -- Rs. 150");


		String tempStr = "menuListJsonDataParse(" + details.toString() + ")";

		return tempStr;



6. Now the Cordova Android project (CordovaJQueryExample) is ready. Now you need to build the project. Building the project will create .apk file. You can copy the .apk file to any device with android OS. To run with eclipse, you need to create an Android emulator. To create emulator, you can go through my tutorial,,,

Now run the project

Run the project JQ


Output Jquery1

Now click on Veg and select dish from the drop-down box

Output Jquery2

Output Jquery3


Similarly, click on Non-Veg radio button and select any dish from the drop-down list

Output Jquery4

Output Jquery5

When we select any radio button, jquery sends the request to the server through ajax call. The server returns the JSON array data.  The received JSON data is parsed and displayed in the drop-down list.

Reference : Apache cordova documentation

Leave a Reply