How should I get the Ajax response from the servlet? - java

I have an Ajax request coming from client side after a key press. The servlet returns a string.
How should I grab this string on the client side? It should be split on "," on the client side and display the list. We are using Velocity for rendering the HTML.
Servlet code:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String acInfo = request.getQueryString();
SomeDAO dao = new SomeDAO();
ArrayList<String> results = dao.acResults(acInfo);
StringBuilder sb = new StringBuilder();
int count = 0;
for (String acResult : results) {
sb.append(acResult);
count++;
if (count == results.size()) {
break;
}
sb.append(',');
}
out.println(sb);
out.close();
}

Dont use "async: false" or it will lose all the AJAX meaning.
Do all the stuff you want in the success method. To split by ',', just use split() and to easily iterate arrays use $.each()
$.ajax({ type: "GET",
url: "/YourServletURL",
success : function(text)
{
var list = text.split(',');
$.each(list, function(index, value) {
alert(index + ': ' + value);
});
// This will show the values. Change "alert" for $('div#mydiv').html(value) or so
}
});

If you are not using Jquery then you can use following:
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
  }
}
xmlhttp.open("GET","YOUR_SERVLET_RELATIVE_URL",true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
</body>
</html>

Sounds like a simple jQuery ajax response scenario - can't you handle the response with code of following nature ?
var responseText = '';
$.ajax({ type: "GET",
url: "/YourServletURL",
success : function(text)
{
responseText = text;
}
});
//alert response or process it or display somewhere
alert(responseText);

Related

how to get servlet response in javascript?

how to get servlet response message in javascript variable is there any possible way to get response message in java script?
Html:
<form method="post" id="importForm">
Name<input type="text" name="name"/>
<input type="submit" onclick="importScenarioFromServer();">
</form>
javascript:
function importScenarioFromServer(){
var result = document.forms["importForm"].submit();
}
servlet:
int numberOfRecs = db.setDBValue(dMap);
if (numberOfRecs == 1) {
String result = "success";
response.getWriter().print(result);
}
This can be implemented using ajax either in javascript or by using jquery.
we can serialise form in ajax hit and then can get response data from servlet in success event callback function. below is example...
function getData()
{
var client;
var data;
var url_action="/temp/getData";
if(window.XMLHttpRequest)
{
client=new XMLHttpRequest();
}
else
{
client=new ActiveXObject("Microsoft.XMLHTTP");
}
client.onreadystatechange=function()
{
if (client.readyState==4 && client.status==200)
{
document.getElementById("response").innerHTML=client.responseText;
}
};
data="name="+document.getElementById("name").value+"&file="+document.getElementById("filname").value;
client.open("POST",url_action,true);
client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
client.send(data);
}
Servlet post method
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out=response.getWriter();
log.info("Good");
out.println("Good to go");
}

Changing part of the html page without refreshing whole page

I have a html page and a java application with Thymeleaf templating engine and I'm looking for a tutorial to make a request to the server and render only part of the page based on response.
At this moment, I have some buttons having a link of the same page with a different parameter, my div is created based on attribute articleList (which I receive from the server based on button_id)
HTML:
button 1
button 2
<div class="" th:each="article : ${articleList}">
<p th:text="${article.getText()}">Article</p>
Java:
public class NodController implements IGTVGController {
public void process(
final HttpServletRequest request, final HttpServletResponse response,
final ServletContext servletContext, final TemplateEngine templateEngine)
throws Exception {
final WebContext ctx = new WebContext(request, response, servletContext, request.getLocale());
Integer button_id = Integer.valueOf(request.getParameter("button_id"));
List<String> articleList = getArticleList(button_id);
request.getSession().setAttribute("articleList",articleList);
templateEngine.process("/index", ctx, response.getWriter());
}
I want my buttons to process my index controller and only change the div with the articles and not refresh the entire page.
I have tried using ajax but I didn't find code examples for server-side that I could understand, so I don't know how to process the request and I don't know how to use servlets. Also I didn't manage to send any request to my current controller.
I have also found in thymeleaf api this method:
public final void process(String templateName, IContext context,
IFragmentSpec fragmentSpec, Writer writer)
where IFragmentSpec should "select a fragment of a template to be processed (once read and parsed), discarding the rest of the template" but I couldn't find more information about it as how to use it or if it is what I'm looking for.
this is the javascript code
//get text 1 by ajax
function getText1(urlstarted) {
xmlHttp = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
xmlHttp = new XMLHttpRequest();
if (xmlHttp.overrideMimeType) {
// set type accordingly to anticipated content type
//http_request.overrideMimeType('text/xml');
xmlHttp.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!xmlHttp) {
alert('Cannot create XMLHTTP instance');
return false;
}
var url=urlstarted+"/jsp/viewText1.jsp"; //put the link to ur Ajax page here
xmlHttp.onreadystatechange = startAjaxingText;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
function startAjaxingText() {
if (xmlHttp.readyState != 4) {
document.getElementById('image').style.display='block' ;
document.getElementById('result').style.display='none' ;
}
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
document.getElementById('image').style.display='none' ;
document.getElementById('result').style.display='block';
document.getElementById('result').innerHTML = xmlHttp.responseText;
} else {
alert("There was a problem with the request.");
}
}
}
//get text 2 by ajax
function getText2(urlstarted) {
xmlHttp = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
xmlHttp = new XMLHttpRequest();
if (xmlHttp.overrideMimeType) {
// set type accordingly to anticipated content type
//http_request.overrideMimeType('text/xml');
xmlHttp.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!xmlHttp) {
alert('Cannot create XMLHTTP instance');
return false;
}
var url=urlstarted+"/jsp/viewText2.jsp"; //put the link to ur Ajax page here
xmlHttp.onreadystatechange = startAjaxingText2;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
function startAjaxingText2() {
if (xmlHttp.readyState != 4) {
document.getElementById('image').style.display='block' ;
document.getElementById('result').style.display='none' ;
}
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
document.getElementById('image').style.display='none' ;
document.getElementById('result').style.display='block';
document.getElementById('result').innerHTML = xmlHttp.responseText;
} else {
alert("There was a problem with the request.");
}
}
}
now your buttons will look like this
<input name="button_1" id="button_1" type="button" value="button_1" onclick="getText1('<%=request.getContextPath()%>');" />
<input name="button_2" id="button_2" type="button" value="button_2"
onclick="getText2('<%=request.getContextPath()%>');" />
your div will look like
<div id="image" style="display:none"><img src="<%= request.getContextPath()%>/images/ajax-loader.gif" alt="Loading...."/> </div>
<div id="result" style="display:none"></div></td>
your viewText1.jsp page that doing ajax part
out.println("text1");//or any logic u want
your viewText2.jsp page that doing ajax part
out.println("text2");//or any logic u want
note that : the result of viewText1.jsp or viewText2.jsp must be a text either a table or paragraphs
Client-side implementation
You will have to use AJAX to load content from the server dynamically.
Consider designing your frontend as SPA. Look into AngularJS or Knockout.
Also, you can use old-school approach by using something like jQuery AJAX if this is just a small area of your application.
Separation of concerns
I strongly suggest to consider the idea to separate concerns by using server as a REST service and frontend as a client. This is the best practice for large applications if you want to keep them maintainable and scalable.
You should look for tutorials of how to implement REST with your server-side technology. It's very common practice so I think you should be able to find one.
If you have any questions I will be glad to update this answer.

when I call jsp by using ajax then jsp returns lots of extra contents specially all html tag

I am busy quite with my new project where I working on jPlayer, completely based on jQuery.
I am very new in jQuery so I am facing lots of problems but now I am little comfortable with jQuery.
My requirement is to access a absolute url if the given url is relative, for that I used some java code. Each and every thing is working well but to fetch the absolute url I used java code for that I used jsp page and execute that using ajax call. Problem is the value returning from jsp is having lots of extra datas, generally all the html tags. I saw this question is already asked by some person and the reply
"use servlet instead of jsp because jsp for presentation and this will output some html".
and my codes are:
function funAJAX(songURL){
var path=document.getElementById("url").value,
ext=songURL.split('.').pop(), // trying to pull extension of link
xmlhttp, absUrl;
//alert(path);
if(window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
// code for IE6, IE5
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
//$("#tempUrl").html(xmlhttp.responseText);
//storing val in div of id="tempUrl"
// absUrl=$("#tempUrl").find("info").text();
//fetching the link only
var v=xmlhttp.responseText;
alert("value from ajax: " + v);
if(ext == "mp3" || ext == "Mp3") { // if absolute url then songUrl val will not change
// alert("extension: "+ext);
ext=ext;
}
else { // if relative link then storing the val returned from ajax as absolute link
// alert("in else part");
songURL=absUrl;
}
alert("i2: song url: " + songURL); // this will execute after returning val from jsp because of ajax call
}
};
// alert("2: song url: "+songURL); //this will execute before sending req to jsp page
xmlhttp.open("GET", "" + path + "/html/player/songURLManipulation.jsp?songURL=" + songURL, true); //calling songURLManipulation.jsp with argument songUrl
xmlhttp.send(); //sending the req
}
above is my jsp page and having lots of tag
"/>
this liferay problems but main thing is to implement jplayer
and my another jsp that one I am calling through ajax is
<%
String songURL=request.getParameter("songURL");
String location=null;
if(songURL!=null) {
HttpURLConnection con = (HttpURLConnection)(new URL(songURL).openConnection());
con.setInstanceFollowRedirects( false );
con.connect();
location = con.getHeaderField("Location");
response.getWriter().print(location);
out1.print(location);
}
//return location;
System.out.println("from song manipulation.jsp: "+songURL);
%>
I achieved this one by using serveResource method and calling that method by ajax by using json object but my question is, is it really not achievable through jsp page return value if I call through above describe way.
It is really good to be part of this forum.
my ajax code
function funAJAXServlet(songURL,servletURL)
{
alert("from ajax fun");
jQuery.ajax({
url :servletURL,
data: {"songURL":songURL},
type: "GET",
dataType: "json", //describe the type of value returned from serveResource class
success: function(data) {
//to put data data into div part of html and data is coming from serveResource class.
var jsonobj=data.songUrlServlet;
alert("from servlet ajax: "+jsonobj);
}
});
}
and my serveResource method
public void serveResource(ResourceRequest request, ResourceResponse response)
{
String songURL=request.getParameter("songURL");
JSONObject jsobj=null;
String location=null;
HttpURLConnection con;
System.out.println("songURL from serveResourceUrl servlet method: "+songURL);
if(songURL!=null)
{
try
{
con = (HttpURLConnection)(new URL(songURL).openConnection());
con.setInstanceFollowRedirects( false );
con.connect();
location = con.getHeaderField("Location");
System.out.println("$$$$$$$$$$$4 location val: "+location);
jsobj = JSONFactoryUtil.getJSONFactory().createJSONObject();
if(location!=null)
jsobj.put("songUrlServlet",location);
else
jsobj.put("songUrlServlet","null");
PrintWriter writer = response.getWriter(); //writing to the client page
writer.write(jsobj.toString());
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
//return location;
else
System.out.println("from song serveResource method: "+songURL);
}
This is working fine.

How to Edit input type text field created from servlet

I have created a text field from servlet
out.println("<input type='text' class='userValue' />");
it shows properly in my page. but when i click on the field it does not allow me to type anything.
I mean normally u see a bar blinking when u type. This blinking is not showing.
It behaves like un-editable text field (I am using jQuery ajax call to put this from servlet to my page)
How to resolve this?
complete code
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String noOfNodeSt = request.getParameter("numberOfNodes");
String action = request.getParameter("action");
PrintWriter out = response.getWriter();
try {
if (action.compareTo("actionOnSelectedNode") == 0) {
int numOfSelectedNodeReceived = Integer.parseInt(request.getParameter("numberOfNodes").toString());
for (int i = 0; i < numOfSelectedNodeReceived; i++) {
out.println("<select class='nodeFromDB"+i+"'>");
out.println("<option>Servlet Action1</option>");
out.println("<option>Servlet Action2</option>");
out.println("</select>");
out.println("<input type=\"text\" name=\"userValue\" />");
}
}
} finally {
out.close();
}
}
JS Code
$(function() {
$('#nodeType').bind('change', function(ev) {
var value = $(this).val();
if (value === 'Single Node') {
//alert("g");
document.getElementById("spanSetNoOfNodes").innerHTML = "<input type='text' value='1' class='textBoxNoOfNode' readonly/><input type='button' value='Generate' onclick='tfc();' class='generateButtonAction' id='generateButtonAction'/>";
} else if (value === 'Multiple Nodes') {
//alert("g");
document.getElementById("spanSetNoOfNodes").innerHTML = "<input type='text' value='1' class='textBoxNoOfNode'/><input type='button' value='Generate' onclick='tfc();' class='generateButtonAction' id='generateButtonAction'/>";
}
$(document.body).on('click', 'input', function() {
//alert($('.textBoxNoOfNode').val());
$.ajax({
url: 'http://localhost:8080/M08CDECUStructuralOptimiser/Interface1?action=actionOnSelectedNode',
data: {numberOfNodes: $('.textBoxNoOfNode').val()},
success: function(response) {
//$('.upItemName').append(response);
document.getElementById("test3").innerHTML = response;
}
});
});
});
});
It was probably replacing the response over and over
i added the onclick='tfc(); and moved the following part in it
$(document.body).on('click', 'input', function() {
//alert($('.textBoxNoOfNode').val());
$.ajax({
url: 'http://localhost:8080/M08CDECUStructuralOptimiser/Interface1?action=actionOnSelectedNode',
data: {numberOfNodes: $('.textBoxNoOfNode').val()},
success: function(response) {
//$('.upItemName').append(response);
document.getElementById("test3").innerHTML = response;
}
});
});
now its working fine

Why Ajax Function XMLHttpRequest called from commandlink using onclick doesn't work?

My problem is when I call some function than render in a definite div, not send my request.
This is my function.
<script type="text/javascript">
//<![CDATA[
function ajaxFunction() {
var xmlHttp;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
return xmlHttp;
} catch (e) {
// Internet Explorer
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
return xmlHttp;
} catch (e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
return xmlHttp;
} catch (e) {
alert("Tu navegador no soporta AJAX!");
return false;
}}}
}
function CargarDatos(_pagina,capa) {
var ajax;
ajax = ajaxFunction();
ajax.open("POST", _pagina, true);
ajax.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
ajax.onreadystatechange = function()
{
if (ajax.readyState==1){
document.getElementById(capa).innerHTML = " Aguarde por favor...";
}
if (ajax.readyState == 4)
{
document.getElementById(capa).innerHTML =
ajax.responseText;
}}
ajax.send();
}
And this is the line where I call this function
<li><h:commandLink action="#{personal.cargarEvento}" onclick="CargarDatos('pages/Politica/nacional/inicio.html','content'); " value="Nacional" >
If I use this line the render works
<li><h:commandLink action="#{personal.cargarEvento}" onclick="mojarra.jsfcljs (CargarDatos('pages/Politica/nacional/inicio.html','content')); " value="Nacional" >
But generate a JavaScript error and not call my Bean.
The target is when I click some element render other page in a div and simultaneously execute some method in one bean.
What is wrong?
How can I make it work?

Categories

Resources