I have an ajax call to a jsp page with certain data.
$.ajax({
type: "POST",
url: "jsp/order.jsp",
data: {
"dishId" : id,
"dishPrice" : price,
"dishName" : name
},
success: function(msg) {
alert(msg);
}
});
I want to read the data in the order.jsp using jstl. However I am not able to do that using the following statements.
<c:out value='${dishName}' />
<c:out value='${dishId}' />
I know it can be done using scriptlets but wanted to do it using jstl.
All HTTP request parameters are in EL available via implicit ${param} mapping.
So, this should do:
<c:out value="${param.dishName}" />
<c:out value="${param.dishId}" />
See also:
Java EE 5 tutorial - Expression Language - Implicit Objects
Unrelated to the concrete problem, do note that there's quite a difference between "JSTL" and "EL". Those <c:xxx> things are JSTL tags. Those ${...} things is EL. You can also use EL standalone:
${param.dishName}
${param.dishId}
However, that opens a potential XSS attack hole, hence the need for <c:out> to escape it.
And, you'd better use a servlet instead of a JSP to deal with HTTP requests. See also How to use Servlets and Ajax?.
Related
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...
I am learning ASP.NET MVC. I have to submit a to controller side after validation in client-side(in jquery). How this can be done? Should i use <form action="#" method="post"> instead of <form action="Controller/Method" method="post"> and add an event handler in click event of submit button of , to send via ajax etc? What should i do? pls help
You are on the right track, and what you suggested will work.
A better method would be to leave the original action intact, providing backwards compatibility to older browsers. You would then create the event handler as normal, and include code to prevent the default submit behavior, and use ajax instead.
$('#submitbutton').live('click', function(e){ e.preventDefault(); });
The easiest way to do this is to use the jQuery forms plugin.
This is my go-to plugin for this type of thing. Basically it will take your existing form, action url etc and convert the submission to an ajax call automatically. From the website:
The jQuery Form Plugin allows you to easily and unobtrusively upgrade
HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit,
gather information from the form element to determine how to manage
the submit process. Both of these methods support numerous options
which allows you to have full control over how the data is submitted.
It is extremely useful for sites hosted in low cost web hosting
providers with limited features and functionality. Submitting a form
with AJAX doesn't get any easier than this!
It will also degrade gracefully if, for some reason, javascript is disabled. Take a look at the website, there are a bunch of clear examples and demos.
This is how I do:
In jQuery:
$('document').ready(function() {
$('input[name=submit]').click(function(e) {
url = 'the link';
var dataToBeSent = $("form#myForm").serialize();
$.ajax({
url : url,
data : dataToBeSent,
success : function(response) {
alert('Success');
},
error : function(request, textStatus, errorThrown) {
alert('Something bad happened');
}
});
e.preventDefault();
});
In the other page I get the variables and process them. My form is
<form name = "myForm" method = "post">//AJAX does the calling part so action is not needed.
<input type = "text" name = "fname"/>
<input type= "submit" name = "submit"/>
<FORM>
In the action page have something like this
name = Request.QueryString("fname")
UPDATE: As one of your comment in David's post, you are not sure how to send values of the form. Try the below function you will get a clear idea how this code works. serialize() method does the trick.
$('input[name=submit]').click(function(e){
var dataToBeSent = $("form#myForm").serialize();
alert(dataToBeSent);
e.preventDefault();
})
I am currently utilizing CF session management and have been investigating transitioning to utilizing J2EE session management. In my attempts to do so, ajax requests made ( when CFsession management is set to use J2EE sessions ) to CF cfc remote methods fail the verifyclient authorization. The code below works when session management uses CF session management.
My assumption is that the _cf_clientid is no longer the correct value to pass to the remote method - as it is generated using cfid and cftoken.
How do I successfully implement J2EE session management and utilize remote cfc methods with verifyclient? Or can it not be done? Using CF tag cfajaxproxy is not an option.
The example code below demonstrates how to use jQuery ajax to call a remote cfc method with verifyclient='true', even though CF documentation indicates that the use of cfajaxproxy is required. This is not the case. (Thanks to Ray Camden and DWMommy. ) This leads me to believe that there may also be a work-around to implement a similar method for verifying a client when using J2EE sessions.
Thanks in advance!
<script src="/plugins/jquery-1.7.2.min.js" type="text/javascript" language="Javascript"></script>
<cfajaximport />
<script>
$(function() {
$.ajax({
url: 'test.cfc',
type: 'get',
dataType: 'json',
data: {
method: 'sayHello',
yourname: 'Foo'
,_cf_clientid: _cf_clientid
},
success: displaySearchResults
});
});
</script>
<script>
function displaySearchResults(res){
$('#searchResults').html( res );
}
</script>
<div id="searchResults"></div>
test.cfc
component{
remote any function sayHello ( string yourname = 'anonymous')
returnformat='JSON' verifyclient='true'{
return 'Hello ' & arguments.yourname;
}
}
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
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...