Wednesday, 3 August 2011

IMPLEMENTING AJAX FUNCTIONALITY USING JQUERY + JSON FRAMEWORK

 
In our old project we are using json framework to achieve ajax functionality.

PLEASE DOWNLOAD THE REQUIRED JSON JAR FILE . WE ARE USING "json-rpc-1.0.jar" JAR FILE.

I want to share the code which can be useful for the readers.

Let us say we want to re-populate the select option dropdown when user changes a value in the existing dropdown.


In the html form contains below code:

<select id="demoSelect" name="demoSelect">
<option value="1">One</option>
<option value="2">Two</option>
</select>


JavaScript Code implementing json looks like below


$("select[name^='demoSelect']").bind('change', function(event)
{
//var e = document.getElementById("demoSelect"); //Get the actual element
var id = event.target.id; //Get the id of the LOV that was changed
var e = document.getElementById(id); //Get the actual element
var i = e.selectedIndex;
var t = e.options[i].text; //Get the text
alert("came here...." + t);

var frmdata = {taskStatusTypeName : t} ;
var myurl = 'demoServlet';
alert(myurl);
var options = {
type: 'GET',
url: myurl,
data: frmdata,
cache: false,
dataType: 'json',
error: function(xhr, textStatus,errorThrown){
alert('An error occurred! ' + errorThrown) ;
},
success: function(data,textStatus){
alert("came here..........success");
var elName = '#demoSelect';
var reasonSelect = $(elName).children().remove().end() ;
for (var i=0;i<data.length;i++){
if (i==0){
reasonSelect.append('<option value="' + data[i].key + '" selected="true">' + data[i].value + '</option>') ;
/* var noteName = '#newNote_' + index ;
var noteVal = data[i].value ;
$(noteName).val(noteVal) ;
*/
}
else{
reasonSelect.append('<option value="' + data[i].key + '">' + data[i].value + '</option>') ;
}
}
$(elName).focus(); //Set focus to the new note input
}
} ;
$.ajax(options) ;

});

As correctly observed it tries to call the underlying backend servlet to fetch the data.

Our servlet code goes like this and donot forget to add the entries in web.xml !

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

public class DemoJsonServiceServlet extends HttpServlet{

private static final String CONTENT_TYPE = "application/json" ;

public DemoJsonServiceServlet() {
}

private static Logger _logger = Logger.getLogger(DemoJsonServiceServlet.class);

public void init(ServletConfig config) throws ServletException
{
super.init(config);
}

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String taskStatusTypeName = request.getParameter("taskStatusTypeName");
response.setContentType(CONTENT_TYPE) ;
response.setHeader("Cache-Control","no-cache") ;
response.getWriter().write(getJson(request,taskStatusTypeName)) ;
}

private String getJson(HttpServletRequest request,String taskStatusTypeName) throws ServletException {

if (_logger.isDebugEnabled()){
_logger.debug("Task status type " + taskStatusTypeName) ;
}

try {
JSONArray jsonKeyValues = new JSONArray() ;
for(int i=0;i<10;i++) {
JSONObject jsonObj = new JSONObject() ;
jsonObj.put("key","key" +i) ;
jsonObj.put("value","value" +i) ;
jsonKeyValues.put(jsonObj) ;
}
return jsonKeyValues.toString() ;
} catch (Exception e) {
_logger.error("Error in Json service" + e.getMessage()) ;
throw new ServletException(e);
}
}

}

Hope this explanation helps.

8 comments:

Anonymous said...

οbviously likе your website but yοu haѵe
tо take a looκ at the ѕpellіng on quite a feω of your
ρoѕtѕ. Sevеral οf thеm aгe rife with
spelling issues and ӏ tо find it vеry tгoublеsome to
inform the truth then again I wіll ѕurely come back agаin.



Fеel free to ѕurf to mу web blog www.palsra.net

Anonymous said...

It's the best time to make some plans for the future and it is time to be happy. I've read this post and if I could I want to suggest you some interesting
things or tips. Perhaps you could write next articles referring to this article.
I want to read more things about it!

Here is my website :: dreambox

Anonymous said...

Excellent blog here! Also your site loads up fast!
What web host are you using? Can I get your affiliate link to your host?
I wish my web site loaded up as fast as yours lol

My weblog - cccam download

Anonymous said...

continuously i used to read smaller articles or reviews that also clear their motive,
and that is also happening with this paragraph which I am reading here.


Look at my blog post: cccam servers

Anonymous said...

What's up to every body, it's my first go to see of this website; this weblog
consists of remarkable and in fact good data in favor of visitors.


My blog post: server For cardsharing

Anonymous said...

Terrific article! This is the kind of information that are meant to
be shared across the web. Disgrace on the
seek engines for not positioning this post higher! Come on over and talk over with my site .
Thank you =)

my web-site - Premium Cardsharing

Anonymous said...

you're really a good webmaster. The website loading pace is incredible. It kind of feels that you're doing any
distinctive trick. In addition, The contents are masterpiece.
you've performed a excellent job on this matter!

Take a look at my webpage ... premium card share

Anonymous said...

Hi there, its good piece of writing about media print, we all
be aware of media is a impressive source of information.


Feel free to visit my weblog ... cccam for sky Italia