i have some.jsp file which also contains javascript/jquery. i need to do below check in javascript part of some.jsp file.based on the condition i need to display a message/ forward the request to servlet which in turn servlet forwards to other.jsp.
I wrote below code:
<script type="text/javascript">
$(document).ready(function() {
var isInIframe = (parent !== window);
if (!isInIframe) {
$.ajax({
type: "GET",
url: "./screenInitializer",
success: function() {},
error: function(ob,errStr) {
alert("Failed. Try Again.","error");
}
});
}else{
$("#accessDenied").text('Access Denied');
}
});
</script>
I can call a servlet using jquery ajax. forward request to jsp is not working.it is displaying a blank page instead of other.jsp. forwards request to other.jsp as below.
//Keeps some values using request.setAttribute() then forward the request
request.getRequestDispatcher("/WEB-INF/other.jsp").forward(request, response);
Basically i dont want any response from ajax call. it just need to call the servlet which in turn servlet forwards to the jsp and displays other.jsp.all My jsps are in WEB-INF folder. Am i doing anything wrong?
Thanks!
Related
Environment: IE7, jQuery 1.1 , Struts 1
Context: Making an ajax call to a Java method which, and the end, reloads the same jsp.
The steps are: jsp A -->request to java method-->doing some stuff-->ActionForward to jsp A, which is returned in the response.
Actually I'm doing this with a single request using location.href and it's working properly.
Now I need to handle multiple requests and conditions and the only way I thought was by using nested ajax calls with async:false, but that's not the point.
The problem is ajax does not reloads the jsp like location.href does.
This jsp is just a smaller part of the main jsp, so I'm not reloading the whole jsp. I guess I have to handle the response in some way, but how?
Call with location.href:
<script>
function myFunction(){
location.href = 'path/to/java/method=with_some_parameters';
}
</script>
Call with ajax:
<script>
function myFunction(){
jQuery.ajax({
url:'path/to/java/method=with_some_parameters'
async:false,
success:function(data){
//nested ajax
}
});
}
</script>
There is a similiar question:
Reload a page after jquery ajax call,
but it didn't help.
Another: How to manage a redirect request after a jQuery Ajax call, this looks better. I'm trying some things.
As I got the full html in the response ('data' in my case), It worked using
function myFunction(){
jQuery.ajax({
url:'path/to/java/method=with_some_parameters'
async:false,
success:function(data){
document.open();
document.write(data);
document.close();
//nested ajax
}
});
}
Source Replacing Entire Page Including Head Using Javascript
Here is my function. I am trying to get the data from the JSP page below. Both files are at the same location. What is my mistake?
sample.js(included in some file):
function getUnits(){
$.ajax({
url:"../js/addunits.jsp",
success: function(returndata){
alert(returndata);
}
});
}
JSP Page addunits.jsp:
<%
out.print("hi");
>%
In a HTML page, I have a select list.
On change, this function getunits will be called.
$("#select").change(function() {
getUnits();
var e = document.getElementById("select");
var SelValue = e.options[e.selectedIndex].text;
document.getElementById('crs').innerHTML = SelValue;
});
You forgot to flush a buffer.
<%
out.print("hi");
out.flush();
%>
EDIT:
It was an assumption at the first place in case if you have a success status code for the ajax call and it might be in particular scenario like yours but not in all cases because if you used that javascript included in some file, then you might make the same mistake twice. When building some URL on the page don't use a relative path in the code, especially if the page is dispatched/included from different places. Next in the absolute path you should include a context path either ${pageContext.request.contextPath} or use JSTL's <c:url> tag. You can do it for loading sample.js but not inside it because you can use the JSP stuff only on JSP page. So, you can build the URL in the JSP and pass it as parameter to js function like that
sample.js:(included in some file)
function getUnits(theUrl){
$.ajax({
url: theUrl,
success: function(returndata){
alert(returndata);
}
});
}
So, in JSP page (you should use jsp folder where you should keep JSP pages) use
<script>
...
getUnits('${pageContext.request.contextPath}/jsp/addunits.jsp');
...
</script>
I know I am doing something stupid and wrong but I can't figure it out. Please help.
I am using Apache Tomcat Servlet 7 with JQuery.
On my web page, when I click on a button, a Jquery GET call is made to my servlet URL. The servlet, after receiving the data (in JSON format), processes the data and creates some result parameters. Then the servlet passes those parameters to a JSP file to load the JSP page. So in summary, when the user clicks on a button, processing happens on the servlet and the result JSP page is loaded.
The problem is, when I make a Jquery GET call from the button, no result page is loaded. Instead when I do console.log(request), I see the entire html content of the rendered JSP page.
Here's my code on the web application when the button is clicked:
var request;
if (request) {
request.abort();
}
request = $.ajax({
cache: false,
type: 'GET',
url:'http://<MyServerAddress>:8080/<App>/<Servlet>',
data: {
'queryType' : 'clickButton',
'data' : JSON.stringify(buttonPageInfo)
},
});
request.done(function (response, textStatus, jqXHR){
console.log("Response: " + JSON.stringify(response));
// shows the entire html content of the processed JSP page that I want to load
});
Here's the code on the server side:
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
processData(request, response);
}
protected void processData(request, response) {
/* Do some processing on the data and come up with results */
RequestDispatcher rd = getServletContext().getRequestDispatcher("/myJSPPage.jsp");
rd.forward(request, response);
}
Right after rd.forward(request, response), I expect my web page forward to myJSPPage.jsp to show the result, but nothing happens. Instead console.log("Response: " + JSON.stringify(response)); shows the entire HTML content of the JSP page with the results I am expecting.
What am I doing wrong?
You are getting HTML because you are forwarding to a JSP.
Just remove the RequestDispatcher stuff and make sure that you have flushed the response data.
Just call windows.open() if you want to do a normal page call. No need to use ajax for that.
How to pass bean values from parent jsp to child jsp in struts2?
My current application is built on Struts 1.2.
In this, when the form is submitted, entire jsp is submitted. And another (or same) jsp is loaded with the bean values.
I am trying to implement a single page application in my current application. Instead of loading/submitting entire page, I'm calling the jsp through ajax. It returns the html of the required jsp and the html is appended in the main jsp.
So there is only 1 main jsp which is redirected through struts action.
I'm calling the bean values in the main jsp.
My requirement is that when the user clicks any control input, How can I pass the bean values(data) to the new jsp which is loaded in the main jsp through ajax.
How can I pass the bean values(data) to the new jsp?
I'm novice to struts2. Any help is appreciated. Thanks.
Edited:
Please find the code which appends the html through ajax:
The div in which the html is appended:
JSP:
<div class="dynamic-loaded-content">
</div>
and HTML name which is loaded on ajax: index-calender.html
This name is passed in the following method:
JS:
function dynamic_file_linker(path) { /* loader display */
$('.loading-bg').show();
$('.loading-img').show().offset({
top: $(window).height() / 2,
left: $(window).width() / 2
});
$('.tool-tip').hide();
$.ajax({
url: path,
type: 'GET',
dataType: "text",
success: function(result) {
$('.dynamic-loaded-content').empty().append(result);
$('.loading-bg').fadeOut();
page_align();
},
error: function() {
alert('Sorry! The page cannot be loaded.');
}
})
}
You can pass form data over AJAX using the FormData object:
var formData = new FormData(form);
xmlHTTP.send(formData);
Where xmlHTTP is your ajax request object and form is your form. This will pass all the data from the form to the action you are calling.
See here for details of this technique:
https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects
Ajax function
$.ajax({
url: path?form_data1='+ $("#data1").val()+'&form_data2='+$("#data2").val()+',
type: 'GET',
success: function(result) {
//your stuff
},
error: function() {
alert('Sorry! The page cannot be loaded.');
}
});
struts.xml
<action name="path" class="controller.UrlActionClass">
<result name="success">result.jsp</result>
</action>
UrlActionClass.class
private String form_data1;
private String form_data2;
//getter and setter method
ajax success page...
placed the result.jsp page to your div tag.
I am having a problem. I have a form submit that uses jQuery JSONP to make a call BACK to my servlet. This code is embedded in another domain, hence the usage.
Here is my form submit AJAX:
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js' type='text/javascript'></script>
<script language='Javascript' type='text/javascript'>
$(\"#form1\").submit(function(event) {
event.preventDefault();
var $form = $(this),
choice2 = $form.find( 'input[name=\"personChoice\"]' ).val(),
url = $form.attr( 'action' ),
$.ajax({
data: {choice:choice2},
url: url,
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'updatePage'
});
});
function updatePage(renderHTML) {
alert(renderHTML);
}
</script>
I can confirm in my Java servlet that the request.getParameter("callback") is populated with updatePage. What I need to do is send back a response in JSONP format within the Java Servlet. How does one do that? I have something really simple like this at the moment:
Java Servlet code:
response.setContentType("text/javascript");
PrintWriter out = response.getWriter();
String renderHTML = "{ renderHTML = 'Successful'}";
out.println(renderHTML);
I also tried JSON content type response, the alert in my javascript updatePage doesn't get called.
What is the trick with Java servlet's and response back on a jsonpCallback???
A JSONP response must be wrapped inside a function call which is specified in request with callback.
Something like
callback({ renderHTML = 'Successful'});
This should usually be taken care at a filter.
The jsonpCallback property is not what you think it is. It's a string (or a function returning a string) which jquery will use as part of the request URL. You can set it to false if you don't need that functionality. See the docs
You should use the 'success' property to set the response handler.
Something like this:
$.ajax({
data: {choice:choice2},
url: url,
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: false,
error: function(xhr, status, error) {
alert("error");
},
success: updatePage
});
Also, the best content-type to use for JSONP is application/javascript.
Hope that helps.