Sending Request to JSP file based upon AJAX POST [duplicate] - java

This question already has an answer here:
JSP not returning data to JQuery AJAX
(1 answer)
Closed 4 years ago.
I am trying to send a post request to Java servlet, execute a query based upon this value, and send the information to a jsp file. The query in entered from a text box, and when the user hits enter, I need to jump to a new page to display the value of the query.
This is my post request to the servlet:
$.ajax({
"type": "POST",
// generate the request url from the query.
// escape the query string to avoid errors caused by special characters
"url": "Search",
"data": {query : query},
"success": function(data) {
console.log("normal search successful");
},
"error": function(errorData) {
console.log("lookup ajax error")
console.log(errorData)
}
})
I get the AJAX post with:
String title = request.getParameter("query");
//peform action to get results...
then forward request to JSP page with:
request.getRequestDispatcher("movielist.jsp").forward(request, response);
I am getting no errors but the screen doesn't redirect to the new page in my app...
Am I missing something major here?

Nothing happens because you do AJAX call - the request happens in the background of the page, and therefore when ajax receives response from JSP - it stays "in the background" - the success handler is triggered.
What you could do - is to do regular form submit - then navigate from JSP as you mentioned.
Otherwise - if you prefer to keep AJAX, you can do a redirect manually in the success handler with:
"success": function(data) {
window.location = "<your URL here>";
...
The URL to redirect to you can pass from JSP that can return json object with it. Hope this helps.

AJAX works correctly, if you look # console it should be print a line. Do your redirect part in your success block.

Related

How to let my configured session work in AJAX

I have this interceptor function where I configure my session.
if (request.getRequestURL().indexOf("profile") > 0) {
if (session.getAttribute("access").equals("sub-admin")) {
System.out.println("This is request to profile - admin");
} else {
System.out.println("This is request to profile - user");
response.sendRedirect(request.getContextPath() + "/error"); //ERROR HERE YOU ARE JUST A USER NOT AN ADMIN, I WILL REDIRECT YOU TO ERROR PAGE
}
}
Now I am using jQuery and AJAX in my front end.
If I am just a user and I will access localhost:8080/sample/profile, It will work. It redirected me to the error page.
But, when I access it in my menu in the home page and click profile, it doesn't work.
I think it is because I am using AJAX and the path doesn't change, the view only.
$.ajax({
url: ROOT_URL + '/sample/profile',
type: "get",
dataType: "text"
}).done(function(data) {
$('#idcontainer').html(data);
});
How do you let the session work in my AJAX front end?
If you'd like to handle the redirect from an AJAX call, you can take a look at the following question:
How to manage a redirect request after a jQuery Ajax call
A better solution might be to check if the request is AJAX, and send a JSON response with an HTTP status that you can handle on the frontend:
JSON Response:
{
"error": "Unauthorized",
"message": "You must be logged in to view this content",
"code": 401
}
And in your interceptor:
boolean ajax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
if (ajax) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().write(responseToClient);
response.getWriter().flush();
response.getWriter().close();
} else {
response.sendRedirect(request.getContextPath() + "/error");
}
Note that not all AJAX libraries include the X-Requested-With header, but jQuery along with most other modern libraries do.
Then in your JavaScript function:
$.ajax({
url: ROOT_URL + '/sample/profile',
type: "get",
dataType: "text"
}).done(function(data) {
// handle success HTML
}).fail(function (data) {
// parse JSON and alert error message
});
In addition, it seems that you're using the AJAX request to replace the contents of the page with the HTML returned from the AJAX request. Instead of using a JSON response, you could also just return the error HTML instead and display that in the same way that you are returning the profile HTML content:
HTML response:
<h1>Error</h1>
<p class="error">You must be logged in to view this content.</p>
And set the HTML the same way as in your done callback:
.fail(function (data) {
$('#idcontainer').html(data);
});

Struts 2 Interceptor redirection not working with Ajax

I have configured Struts 2 Interceptor for validating the user session. On invalid session I am redirecting to an error page.
The Interceptor is working fine for the normal calls to the action classes but the error page redirection is not working when I am calling an action class through ajax call.
What I am currently doing for this is sestting a request attribute in the interceptor and on the JSP based on that attribute value redirecting from the JSP.
But instead of what I am doing is there any way by which I dont need to write any thing in JSP for error page redirection to work in the similar way when calling the action class in a normal way and in the form of Ajax
Thanks,
Vinay
In the interceptor, set the response status to UnAuthorized just before we return the errorpage.
httpResponse.setStatus(HttpStatus.SC_UNAUTHORIZED);
return "errorPage";
In the ajax call where we make a request that ends up in session timeout and redirect, put a error handling block and redirect to the page directly here.
$.ajax({
url : "some.action",
data : {
"query" : inputText
},
type : 'GET',
dataType : 'json',
success : function(data) {
//code
},
error : function(data) {
if (data.status == 401 ){
console.log("UnAuthorized. Redirecting to Error");
window.location.replace(contextPath +"/error.jsp");
}
}
Have a struts entry for the errorpage to avoid any config issues.
<result name="errorPage">errorPage.jsp</result>

HTML from servlet response using ajax is not being executed in JSP page

My problem is kinda weird. I have a JSP page that calls servlet using JQuery/ajax on combobox change. Everything works fine, I get the response but html is displayed as text. Other thing worth mentioning is when I call servlet directly by URL, everything is fine.
Servlet response code:
for(int i=0;i<tabstr.length;i++){
wyjscie.println(i+": "+tabstr[i]+" <br>");
}
JSP ajax call:
$('#com2').change(function() {
$.get('filtr', function(responseText) {
$('#result').text(responseText);
});
});
result is an ID of a DIV inside JSP page. I've done some servlets without ajax in the past and I didn't encounter this problem before. Any idea how to deal with it?
you have to set as html not text try this
$('#result').html(responseText);
I think your server doesn't specify the mime type of the response. So you have to specify it or you can specify dataType in you ajax call.
$.ajax({
url : "myUrl",
dataType : "json",
data : {
param1 : value1,
}
});
ajax api:
dataType: The type of data that you're expecting back from the server. If none
is specified, jQuery will try to infer it based on the MIME type of
the response...

How to respond to a client request from a servlet without reseting the controls in jsp form

I am a building project in which I am using java-beans,jsp and servlets. I need to send the response to the client on the same page from where request was made with a slightly modified html. But when I(server) sent the request to the jsp page, the controls in the form are getting reset to their original value. But I don't want to override the user's input after the request was made. One way to achieve this is to take value of the property for each control in the form when request is made and then set them again while responding. Actually there are a large number of controls in my form, taking values of each doesn't seem efficient.
So is there some other way to keep the form in the jsp file unchanged while responding to the client.
you can use ajax for what you are asking, or you have to save the data on form submit, in session or some place and set them back again while responding. Apart from that I think there is no other way you can retain form data even after page reload.
Thanks
Chakri
Why dont you use iframe ? so you dont have to refresh the whole page when the request is made to the same page.
Instead of making the action of the form to the same page, call a javascript function that set the parameters in the link and then
var f = document.getElementById('iframe');
f.src = 'newlink';
f.contentWindow.location.reload(true);
This populated the iframe with the latest content
function openOffenderInfo(i)
{
$.ajax({
url:'../loginServlet',
type: 'POST',
success: function(data)
{
alert("reset your div values in this block");
.... for example .....
documnet.getElementById('reloading Div').innerHTML=data;
},
error: function(data)
{
alert("error");
}
});
}
URL : c=name of the servlet you want to call
this servlet calculates the data and gives the new data you want to reset in your div
success : this is the function which will be executes if your ajax call is made successfully
so you can set the values of your reloading part inside this function
I hope this might serve you the purpose

What if targeting URL is not returning back

This is the sample code I am using to hit a URL with fixed time interval.
$(document).ready(function() {
var counter = 1;
$.doTimeout( 1000, function() {
$.ajax({
type: "GET",
url: "<%=encodeUrl%>",
timeout: 10000,
dataType: "text",
complete: function(resp) {
if (resp.status == 200) {
$("#msg").html(counter++);
} else {
$("#msg").html("Failed");
return true;
}
}
});
});
});
Target URL is a servlet which is forwarding the control to another JSP. As per my understanding I must be redirected to new page. But it is showing the same page with the counter value 1. Means, redirect from target servlet is not working. And response is coming back to the same page.
When your AJAX response is a redirect to another page, the redirected page will be fetched as the response of your AJAX request, that's why your are getting only 200 as HTTP status.
You cannot handle redirects based on the HTTP Status codes that you receive with AJAX.
An AJAX response cannot redirect you to a different page unless you program it to do so.
So if you want to redirect based on your AJAX response, you should modify your server side code to send you the redirect URL as a response, rather than redirecting.
Refer one of answers with example solution
AJAX isn't meant to redirect. These headers don't get executed by your browser thus letting you stay on that page!
What is the exact code your servlet gives back?
The code is doing exactly what its written to do. You are firing an ajax call, and on response 200 you are setting counter as html for #msg. There is nothing in the code that'll make you redirect to the New Page.
You do not need ajax here if you want to redirect. Else, if your redirect is based on response returned by the servlet, capture it in complete and set window.location.href = 'your/redirect/url/' to load the New Page.

Categories

Resources