wrong ajax response in callback using sitemesh and struts2 - ajax

I've built a simple web application using sitemesh and struts2 frameworks. Now I have some problem getting the right reponse with an ajax callback in a jsp. I'm using with success the same process in another web application, but using tiles with struts 1.
I try to explain the problem.
I have a jsp (decorated with sitemesh from a template called "basic-theme.jsp" with a decorator:title and a decorator:body tag).
The page has an input button, which calls a jQuery.ajax post function:
function checkRicevuta(){
var params = "actionToDo=checkRicevuta&idRicevuta="+$("#idRicevuta").val();
$.ajax({
type: "POST",
url: "addettoReclami",
data: params,
success: function(response){
$("#checkRicevuta-box").append(response);
}
});
}
url is correctly calling an ActionSupport class, which is processing 'params':
if(request.getParameter("actionToDo")!=null && request.getParameter("actionToDo").equals("checkRicevuta")){
logger.info("Avvio procedura di verifica ricevuta fiscale");
String idRicevuta = request.getParameter("idRicevuta");
if(dbController.checkRicevuta(idRicevuta))
request.setAttribute("message", "Ricevuta valida!");
else request.setAttribute("message", "Ricevuta non valida");
return "esitoRicevuta";
}
'esitoRicevuta' forwards to a simple jsp literally made only of two lines:
<% String message = (String)request.getAttribute("message"); %>
<p><%=message %></p>
because I'd like to append this simple response inside a div of the first jsp which made the ajax call.
The problem is that the response is also being decorated by sitemesh, so I pratically get a nested basic-theme.
In the sitemesh xml I set the exclude pattern not to process my /fragment/* path where is located the "response jsp":
<?xml version="1.0" encoding="UTF-8"?>
<decorators>
<excludes>
<pattern>/popup/*</pattern>
<pattern>/fragment/*</pattern>
</excludes>
<decorator name="basic-theme" page="/decorators/basic-theme.jsp">
<pattern>/*</pattern>
</decorator>
</decorators>
I said, using the same process with tiles and struts1, the problem does not happen.
Probably I'm wrong, but I'm supposing this is because response is appended inside the "caller jsp" so sitemesh decorates the page two times, one for the caller jsp's body and one for the fragment inside the caller jsp's body.
So I ask you... why this problem? Is there a solution to avoid this?
Thanks in advance

Related

Displaying error messages in jsp without reloading page

I have a program using jsp and servlets that checks the database for an email address. First the jsp page sends the email to the doPost method of the servlet, then the servlet checks the database, if email exists I use request.setAttribute set a success message and then forward it to the same jsp page, if it doesn't exist it forwards an error message.
The problem i am facing is that it refreshes the jsp page, whereas when I used php for another program i was able to display just by echo without refreshing the entire page.
You can use JQuery Ajax request to do this:
Servlet:
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("good email or not?");
Jsp:
$('#emailButton').click(function() {
$.post('mySevlet', function(responseText) {
if (responseText == 'good'){
$('#statusDiv').text('you are good to go.');
}else{
$('#statusDiv').text('Stop Righ there!');
}
});
});

How to return jsp page in spring mvc 3 ajax call

I have a main page with header, footer, left panel and main content. I want to dynamically change main content on click of left panel. For this I am using ajax call, ajax will call controller and controller will return jsp which I will replace in main content.
But the problem I am facing is that I am getting JSP properly if I am using purely html coding but if I use spring form it is not working.
Do I need to declared taglib in all jsp or only in Dashboard jsp.
If I declare taglib in all child jsp then it not working and I do not declare then form:input do not render in to html
Can we return jsp in ajax call to replace with main content because here it says only #ResponseBody (JSON) can be used in ajax call.
I am using ajax call because I don't want to reload all my header, footer and left panel because they will always remain same.
Ajax code
<script type="text/javascript">
$(".ldMainContent").click(function(){
var actionName = this.id;
actionName = "${pageContext.request.contextPath}/sadmin/forward/"+actionName;
$.ajax({
url:actionName,
type:"POST",
data:"URL",
success:function(result){
$("#mainContent").html(result);
}
});
});
</script>
I am using bootstrap in design
The content can be loaded using jQuery's load method.
The code will be
$(".ldMainContent").click(function(){
var actionName = this.id;
actionName = "${pageContext.request.contextPath}/sadmin/forward/"+actionName;
$("#mainContent").load(actionName);
})
In your controller don't have #ResponseBody it is used to return object as JSON or XML. The controller should return a view for the JSP page which should only have the content that you want inside the mainContent.
Do I need to declared taglib in all jsp or only in Dashboard jsp.
Yes you have to declare the taglibs which ever jsp file you are using the tags.

liferay, jsf. How to javascript json object save to database

Need some help in the following case:
I have set an application as Liferay portlet and i am using JSF/Primefaces for builing my views. For data modelling i am using Hibernate.
In a certain view i load a so called "image annotator" which is using Javascript tools for gathering user input (annotation on an image canvas). This information i would like to be able to save in a file/database and then re-use when the user edits again a specific image.
Here is my view:
<h:head>
<script src="#{facesContext.externalContext.requestContextPath}/js/OpenLayers.js" />
<script src="#{facesContext.externalContext.requestContextPath}/js/image-viewer.js" />
<script src="#{facesContext.externalContext.requestContextPath}/js/xml2js/xml2json.js" />
<script src="#{facesContext.externalContext.requestContextPath}/js/xml2js/xml2json.min.js" />
...
</head>
...
<p:fieldset legend="Viewer">
<p:outputPanel layout="block" styleClass="imageEditorImagePanel" />
</p:fieldset>
....
So the image and the relevant jscript tools (OpenLayers) are loaded in imageEditorPanel placeholder.
The javascript code (image-viewer.js) gathers user input in a json (GEOJson) object, and this object i would like to pass to a back bean controller when Save button (jscript) is selected:
...
//define save button
var save = new OpenLayers.Control.Button({
title: 'Save', text: 'Save',
trigger: function(){
var GEOJSON_PARSER = new OpenLayers.Format.GeoJSON();
var vectorLayerAsJson = GEOJSON_PARSER.write(vlayer.features);
...
So i want to pass 'vectorLayerAsJson' object to a java controller (backbean) ...
I am trying to implement an ajax call like:
jQuery.ajax({
type: 'POST',
url: 'imageannotations',
contentType: 'application/json',
data: vectorLayerAsJson,
success : function(data) { alert("success")}
});
can anybody help on how am i going to make this ajax request as also how am i going to implement my controller class?
You can initiate a call to a java managed bean via Javascript using primefaces p:remoteCommand. Answers how to send the String as an argument can be found here.
In the managed bean/java controller, just have a String variable with getter/setter and an action method to start the unserialization (following is untested code):
#ManagedBean(name="testBean")
public class Test {
public String actionOnString() {
String value = FacesContext.getCurrentInstance()
.getExternalContext().getRequestParameterMap().get("param");
// do your unserialize and actions here
return "";
}
}
Within JSF have something like
<p:remoteCommand name="sendJSONToServer" action="#{testBean.actionOnString}" />
and as javascript on the desired position
sendJSONToServer({param: vectorLayerAsJson});
should do the job.
Direct ajax-push is also possible via PrimePush, using the athmosphere framework. Possibly, that might be overkill for what you try to achieve.
Update 1
Of course, when you get a JSON-Object serialized (so to say "n String format), you have to JSONize it in Javascript - this answer "How to parse JSON in JavaScript" might help you further regarding that.
Hope it helps...

How to get xml data using ajax in jquery?

I want to use ajax in jquery to get data for my page...
The problem is that the url which i call has some query strings to be sent along with it...
for example: the url which i call for getting data is:-
http://mysite.in.dataengine.aspx?t=abcde&token=h34jk3&f=xml
the data i get in response from this url can be in xml format or java script arrays(whichever i choose)
for eg...the xml wil look like this:-
<root version="1.0">
<Regions>
<Region SubCode="MWEST" RCode="west"/>
<Region SubCode="MCENT" RCode="north"/>
<Region SubCode="THAN" RCode="south"/>
</Regions>
</root>
and the javascript array would look like this :-
Region = new Array();
Region.push(new Array('MWEST', 'west'));
Region.push(new Array('MCENT', 'north' ));
Region.push(new Array('THAN', 'south'));
So when i get the data i want to store it in a drop down box.(using ajax)
Note I can get either xml OR javascript arrays as the returned data, not both together.
You can make an ajax call along with parameters like this:
var paramsData = "t=abcde&token=h34jk3";
$.ajax({
type: "GET",
url: "dataengine.aspx",
data: paramsData,
dataType: "xml",
success: function(xml){
//process xml from server
}
});
I would suggest you to get the data in JSON format, as Json comes natively to javascript and it much easliy manipulated using javascript as compared to XML. The easiest way i can see to work on your problem is to store all your data whether xml or json & put it inside a hidden div and then use jQuery to populate that data in a drop down box.
Here is an amazing jquery plugin with example that should ease your work
http://plugins.jquery.com/project/jqueryclientdb
Just parse it. I"m not sure if this will work, but it might:
xml = ...
region = new Array();
$(xml).find('Region').each(function() {
region.push(new Array($(this).attr('SubCode'), $(this).attr('RCode'));
});
Thanks for your help guys...but i have found the solution....Like i said...that i get in return either xml or javascript array...So..i'm using javascript arrays.. and using a function in jquery*($.getScript)* which fetches an external javascript code via ajax...Thus i am getting all my data now through ajax in jquery...

Spring MVC and Ajax Operation using JQuery

I have a JSP page called CreateProcessGroup.jsp and I use an annotation controller to map requests to CreateProcessGroup.htm to that page. But I'm having an interesting issue when I request the page from browser it works, when send a request using jQuery $.get method I get 404 (CreateProcessGroup.htm not found) is there a difference between two requests?
My JSP page just under WebContent dir and JS file under WEBContent/Jquery my function sending the request like below:
function SendCreateProcessGroupRequest()
{
var pid = $('#pid').val();
var description = $('#processGroupDescription').val();
var x = "/CreateProcessGroup.htm";
alert(x);
$.get(x, { pid: 62, description: description },
function(data){
alert("Data Loaded: " + data);
});
}
Do I need to give the URL as ../CreateProcessGroup.htm? Indeed I tried:
/CreateProcessGroup.htm
../CreateProcessGroup.htm
/../CreateProcessGroup.htm
../../CreateProcessGroup.htm
/../../CreateProcessGroup.htm
My guess is DispatcherServlet can not map Ajax requests to Controllers but this is stupid isn't it?
How can i get rid of the situation?
Thanks all.
Try this instead:
var x = "CreateProcessGroup.htm";
If the page you're requesting is beside the one making the request there's no need for a path in front, it will (by default) make a request to the same path just with that page/handler on the end.

Resources