Hello World Example of AJAX using JSON

Here is the code for Hello World AJAX example using JSON:


index.html

<html>
<head>
<title>Ajax JSON Demo</title>
<script type=”text/javascript” src=”script/ajax-script.js”></script>
</head>
<body onload=”setTimeout(‘sendAjaxRequest()’,500);”>
<div id=”resDiv”>
Please wait while the list is being generated…
</div>
</body>
</html>

ajax-script.js

var httpRequest;

function getXHR()
{
var xhr = null;
if (window.XMLHttpRequest) // Mozilla, Safari, …
{
xhr = new XMLHttpRequest();
if (xhr.overrideMimeType)
{
xhr.overrideMimeType(‘text/html’);
}
}
else if (window.ActiveXObject) // IE
{
try
{
xhr = new ActiveXObject(“Msxml2.XMLHTTP”);
}
catch (e)
{
try
{
xhr = new ActiveXObject(“Microsoft.XMLHTTP”);
}
catch (e) {}
}
}

if (!xhr)
{
alert(‘Cannot create an XMLHTTP instance’);
return false;
}
return xhr;
}

function sendAjaxRequest()
{
var reqUrl = “AjaxJsonServlet?list=std”;
httpRequest = getXHR();
httpRequest.onreadystatechange = ajaxCallback;
httpRequest.open(‘GET’, reqUrl, true);
httpRequest.send(null);
}

function ajaxCallback()
{
try
{
if (httpRequest.readyState == 4)
{
if (httpRequest.status == 200)
{
generateStudentList(httpRequest.responseText);
}
}
}
catch(e)
{
alert(‘Caught Exception: ‘ + e.description);
}
}

function generateStudentList(resData)
{
var html = “”;

if(resData != null && resData != “”)
{
html = “<table><tr><th>ID</th><th>NAME</th></tr>”;
resData = eval(resData); // validates the json string and convert it into object
for(var i=0; i<resData.length; i++)
{
var obj = resData[i];
html += “<tr>”;
html += “<td>” + obj.id + “</td><td>” + obj.name + “</td>”;
html += “</tr>”;
}
html += “</table>”;
}
else
{
html = “No data to display!”;
}

var resDiv = document.getElementById(“resDiv”);
resDiv.innerHTML = html;
}

AjaxJsonServlet.java

package com.ajax.json.demo;

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

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

public class AjaxJsonServlet extends HttpServlet
{
public void init() throws ServletException
{
}

public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType(“text/json”);
PrintWriter out = response.getWriter();

String fromPage = request.getParameter(“list”);

if(fromPage != null && fromPage.equals(“std”))
{
String json = JSONGenerator.generateStudentListJSON();
out.write(json);
}

out.flush();
out.close();
}

public void destroy()
{
super.destroy();
}
}

JSONGenerator.java

package com.ajax.json.demo;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JSONGenerator
{
public static String generateStudentListJSON()
{
JSONArray studentList = new JSONArray();
JSONObject jsonObj = null;
jsonObj = new JSONObject();
jsonObj.put(“id”, 1);
jsonObj.put(“name”, “Adnan Sohail”);
studentList.add(jsonObj);

jsonObj = new JSONObject();
jsonObj.put(“id”, 2);
jsonObj.put(“name”, “Asim Riaz”);
studentList.add(jsonObj);

jsonObj = new JSONObject();
jsonObj.put(“id”, 3);
jsonObj.put(“name”, “Hassan Zeb”);
studentList.add(jsonObj);

jsonObj = new JSONObject();
jsonObj.put(“id”, 4);
jsonObj.put(“name”, “Alam Virk”);
studentList.add(jsonObj);

return studentList.toString();
}

}

web.xml

<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app version=”2.4″
xmlns=”http://java.sun.com/xml/ns/j2ee&#8221;
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd”&gt;
<servlet>
<servlet-name>AjaxJsonServlet</servlet-name>
<servlet-class>com.ajax.json.demo.AjaxJsonServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>AjaxJsonServlet</servlet-name>
<url-pattern>/AjaxJsonServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

Build a project in eclipse or some other IDE, and run the following application.

It will results like:

Results-1

Results-1

Results-2

Results-2

4 thoughts on “Hello World Example of AJAX using JSON

  1. good. nice and short example.
    share some more example from yahoo library too.

  2. Thanks!

    ya i’ll design some examples from yahoo and dojo too…

  3. no updates … you can keep live your blog by posting small things .. but REGULARLY … don’t go for long and lengthy contents .. small example… some tweaks ..

  4. I usually unable to find time to post thing here. But now I’m trying…

Leave a comment