Display list values got by Javascript on JSP page - javascript

I have this link on my test.jsp page
<a onclick="treeViewAjax('${searchDummyUrl}/view/${search.DummyNumber}/1')">View</a>
Now when I click on this then treeViewAjax ,A JavaScript method is being invoked as you can see in the linkHere is the treeViewAjax method
function treeViewAjax(Url){
$.ajax(Url, function(data) {
alert(data);
});
}
and at the same time my Spring controller's searchDummyView method invoked
#RequestMapping(value = "/Dummy/searchDummy/view/{dummyNumber}/{dummyTypeId}", method = RequestMethod.POST)
public #ResponseBody
List<Report> searchDummyView(ModelMap modelMap, #PathVariable("dummyNumber") Integer dummyNumber, #PathVariable("dummyTypeId") Integer dummyTypeId) {
List<Report> reportList = new ArrayList<>();
reportList.add(dummyService.readReport(dummyNumber, dummyTypeId));
//modelMap.addAttribute("reportList", reportList);
return reportList;
}
Now when as Spring expert's can understand that I have used #ResponseBody annotation as to make to ajaxical request So it then again send response back to the requested URL.Now here again control is on my JS method treeViewAjax and when I alert the data then it show the list values perfectly. Now I am stuck here that How can I capture reportList returned by searchDummyView method on JSP page as well as How to iterate/Show its value on the JSP page using EL. Any suggestions? Note: I have tried to show reportList like this but it didn't work for me
<c:choose>
<c:when test="${reportList.size() > 0}">
<c:forEach items="${reportList}" var="list">
//iterations over list but
</c:forEach>
...
... />
It did't display anything from list because of my condition < 0 and I guess it is returning 0 size here OR not accessible here.(could be any reason)

This code will not work in your case :
<c:choose>
<c:when test="${reportList.size() > 0}">
<c:forEach items="${reportList}" var="list">
//iterations over list but
</c:forEach>
...
... />
Your JSTL and EL will be processed by the server and sent to the browser . But in your case the JSP is already rendered in the browser and you are firing a AJAX request which will give back some data . You are getting an AJAX response from server , not a full fledged response which the browser will try to render . To create a table with the data of AJAX response I guess there are two options :
Build the table using HTML and javascript dynamically once you get the AJAX response back.
Have a <div> inside your JSP and load another JSP with the table in that AJAX success.

Related

Calling jersey client by button click

I have a jersey client class which is making a put request to a rest.
//JerseyClient
public void putRequest() throws Exception{
reloadUri();
Response response = target.request(MediaType.APPLICATION_JSON)
.accept("application/json;charset=UTF-8")
.header("Content-Type", "application/json")
.header("Authorization", "Basic OTA1MzAwNjY3MDg2OjZ4dDg5dk50VXdCbg==")
.put(Entity.entity(sub, MediaType.APPLICATION_JSON),Response.class);
System.out.println(response);
if(response.getStatus() == 200) {
System.out.println("put request using Json is Success");
}
}
It's working fine, but I wanted to call this function with a button click. And this button is placed on one of my jsp file. So, is there a way to call this request inside that jsp file when button clicked.And redirect the page into new jsp according to response of rest.
No directly by the jsp. If you include this code in the jsp, it will be executed while parsing the jsp page in the server.
You should include it in a Java component which will be called by a Servlet (or controller, filter, etc...). The button in your jsp will make a call to the URL which executes that component, and is there where you must do whatever you need with the result.
If you want to execute directly in the jsp while clicking the button, you must make it using javascript in client side.
You may call this method using URL reference:
define a path annotation for method:
#Path("/PATH")
#GET// or #POST
public void putRequest() throws Exception{
...
}
And then, from you jsp page you can define the button to redirect to this URL to initiate the above method.
You may read more about jersey annotations here.

Liferay - How to render JSP from #ResourceMapping annotated method. This method is being called from a JS file via AJAX

1st JSP: Calls a Javascript function:
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="continueTour" onclick="launchTutorial()">Take a Quick Tour</button>
</div>
Javascript function(s):
function launchTutorial(){
var enjoyhint_instance = new EnjoyHint({});
var enjoyhint_script_steps = [
{
"next #newAuthorizationActive": 'To create an authorization form'
}
];
enjoyhint_instance.set(enjoyhint_script_steps);
enjoyhint_instance.run();
//Here's where i'm accessing the 'exportFile' controller method (shown further below)
$.ajax({
type : "POST",
url : $('#authorizationResourceURL').val(),
data : {action: "redirectToEmpInfoForAuthTour", tourStatus : 0},
success : function(data){
alert('success');
document.open();
document.write(data);
document.close();
}
});
Method in the controller:
#ResourceMapping
protected void exportFile(ResourceRequest request, ResourceResponse response) throws IOException {
String action = ParamUtil.getString(request, "action", "");
if(action.equals("redirectToEmpInfoForAuthTour"))
{
//This is where I want to return the 2nd JSP from
}
A brief context to what exactly I'm looking for here:
I have a JSP (1st JSP), where I'm trying to show the user a tutorial (using enjoyhints) for the portlet. As a part of this tutorial, I need to highlight elements (select boxes, text fields) which are on different pages (JSPs) of the portlet. Hence, In the Javascript function, I first highlight (this highlighting part is whats taken care of by enjoyhints) the element that's there on the 1st JSP (and this works fine), and now I want to show the user the 2nd JSP, and using enjoyhints, highlight some element in the 2nd JSP, and so on in the 3rd and 4th JSPs too.
If anybody has an alternative way of how I can do this, kindly let me know. The main problem here is that the elements I need to highlight are on different JSP pages (of the same portlet). Had all the elements been on the same page, it would've been simple.
I'm using Liferay Portal, and Spring Portlet MVC as my design pattern.
UPDATE: Here's another thing that I've been trying to achieve the same thing, but no luck
You can define resource method as shown below with return type as
ModelAndView and show entire jsp content in popup or append to existing html.
#ResourceMapping
protected ModelAndView exportFile(ModelMap model,ResourceRequest request, ResourceResponse response){
}
You can simply change the signature of your ResourceMappingmethod to return a String.
The return value can be the name of your view (i.e. JSP).

Not getting c# webmethod json sting on another page

I have created a WebMethod (dt) in code behind page c# of default.aspx page, i want to display response data(json string) on another page like default2.aspx page and bind json response data using ng-repeat angularjs
[WebMethod]
public static string getJson()
{
string data = string.Empty;
data = (string)HttpContext.Current.Session["getData"];
return data;
}
WebMethod defined in default.aspx.cs,
I want to bind json data(getting from webmethod) using ng-repeat angularjs in default2.aspx page from button click on default.aspx page. I am getting json string on same page, but don't know that how to show this on another page.
Any suggestion or help....
Just use something like the follwing on your second page i.e Default2.aspx
$.ajax({
url: 'Default.aspx/getJson',
.
.
});

Thymeleaf page refresh followup - Now with AJAX

As a followup to my earlier question about using Thymeleaf and preventing page refresh:
http://forum.thymeleaf.org/Preventing-page-refresh-Thymeleaf-amp-Spring-MVC-td4029155.html
Basically I had a working Spring MVC app that uses Thymeleaf to save form data. When the user saves the data the page would refresh (since I wanted to leave them on the page for more edits) and I wanted to eliminate the page refresh.
I have coded up some Javascript to use JQuery Ajax to post the data to my Spring MVC Controller. The trick seemed to be to not use a submit button, just a regular button and bind a JS function to it for sending the data to the server.
It all seems to work perfectly, but I want to make sure I understand what is happening. In particular I'm wondering if Thymeleaf is now redundant. I don't think it is because when I initially load the page Thymeleaf is still bound to the data bean. From using the debugger on the server side in the controller it looks like the post request calls the mapped method and passes in the data to the model.
I would appreciate your comments on whether or not this is the correct way to accomplish this.
Finally, how do I handle an error, say for example the repository fails to persist the data for any reason?
Thanks very much.
Here are the important parts of the form:
<FORM id="adminDataForm" action="#" th:action="#{/admin_ajax}" th:object="${adminFormAjax}" method="post">
<input type="button" value="Save Changes" id="post" onClick="sendData()" />
Here is the Javascript:
function sendData()
{
$.ajax(
{
type: "POST",
data: $("#adminDataForm").serialize(),
cache: false,
url: "/admin_ajax",
success: function(data)
{
alert("Your changes have been saved");
},
error: function()
{
alert("Error - Data not saved");
}
});
}
Here is the controller:
#SessionAttributes("adminFormAjax")
#Controller
public class TestController
{
final static protected long INDEX_RA = 2L;
#Autowired
private AdminDataRepository rep;
#RequestMapping(value="/admin_ajax", method=RequestMethod.GET)
public String adminFormAjax(Model model)
{
AdminData ad = rep.findById(INDEX_RA);
// If there is no configuration record, create one and assign the primary key
if(ad == null)
{
ad = new AdminData();
ad.setId(INDEX_RA);
}
model.addAttribute("adminFormAjax", ad);
return "adminFormAjax";
}
#RequestMapping(value="/admin_ajax", method=RequestMethod.POST)
public #ResponseBody AdminData adminSubmit(#ModelAttribute("adminFormAjax") AdminData ad, Model model)
{
rep.save(ad);
model.addAttribute("adminFormAjax", ad);
return ad;
}
}
So breakdown of answer.
Thymeleaf not redundant, it will still render the HTML page prior to sending to client. Ajax just does the further processing for you on client side.
You can use submit button as well, you just need to ensure your form is properly structured and you have javascript listening for your submit button click e.g.
$("#submitbutton").on('click', function (){//do stuff});
You handle any and all exceptions/issues within your Ajax controller as you would with standard controller. You need to separate issue handling at different levels. e.g. respository level issues should be managed at rep level, controller/pojo should be at controller level (or pojo if you using one for processing). You should also be capturing any exceptions through a global medium (e.g. ControllerAdvice).
Any issues/errors you pick up you should be communicating back via your return call in adminSubmit, and managing the relevant client response in ajax.

Iterate arraylist value on jsp after got response from ajax

I got the arraylist from the ajax response. How can I assign the values to textbox after getting the response from ajax through arraylist?
while(rs1.next())
{
pabean.setAge(rs1.getString("patient_age"));
pabean.setDalerg(rs1.getString("patient_drug_allergies"));
pabean.setPmhistory(rs1.getString("patient_past_medical_history"));
pabean.setDiet(rs1.getString("patient_diet"));
pabean.setFhistory(rs1.getString("patient_family_history"));
pabean.setTobbaco(rs1.getString("patient_smoke"));
pabean.setDhistory(rs1.getString("patient_drug_history"));
pabean.setAlco(rs1.getString("patient_alcohol"));
pabean.setSleep(rs1.getString("patient_sleep"));
pabean.setGhistory(rs1.getString("patient_ob_gyn_history")
pabean.setPatient_details_id(rs1.getInt("patient_details_id"));
//uid = rs.getInt("patient_details_id");
}
addressLists1.add(pabean);
session.setAttribute("pagup", addressLists1);
out.println(addressLists1);
You said you are getting this value from ajax call.
Do remember you can not get a java object in ajax response. because call is part of javascript and javascript can not access java object.
like the way you are printing the arraylist like out.println(addressList1); it is printing as [com.bridghc.bean.PatientDetailsBean#15f9093f] it's just a string representation of the addressList1 object which serves no purpose.
Second thing you have written code in jsp like
<input type="text" id="txtage" name="txtage" placeholder="Age" class="form-control" value="<%=padetail.get(0).getAge()%>">
so <%=padetail.get(0).getAge()%> is a java code which run at server when you demand for the page even before the ajax call was being made.
You can try this -
if you want to print the age in the jsp just print it on servlet like
out.println(padetail.get(0).getAge());
so now in the ajax response you will get the age.
now you can place that response value in the desired input with jquery like $('#txtage').val(responseData);
if you want your whole list on jsp in response of ajax it's better to use json use any of the json library like google gson or json.org and create json array instead of arraylist and then set mime type to "application/json" and then print it with out.print()
after that you can parse this json in ajax success call and use in whatever way you want.

Categories