Calling servlet to load the data using jquery ajax? - java

I am new to JQuery. I have a servlet which will fetch data from the database and the result is kept is request and the same result is retrieved in jsp file. Now i have to call the servlet using ajax jquery to load the data. I am doing as below. But it is not loading. Please help me.
$('#myForm #revert').click(function() {
$.ajax({
type: "GET",
url: "./myController",
success: function(msg) {
<span style="color:green;font-weight:bold">Successful</span>');
},
error: function(ob,errStr) {
//Todo
}
});
});
Servlet code:
//Service call gets data and the result is kept in request scope as below
request.setAttribute("myresult", result);
request.getRequestDispatcher("/WEB-INF/myScreen.jsp").forward(request, response);
Thanks!

Ajax is not a normal HTTPRequest,You canot Forward or sendRedirect a Ajax request
Since it is Asynchronous,you need to write the response for Ajax request
PrintWriter out = resp.getWriter();
out.println(resultString);
return;
Please read #Balusc great answer :How to use Servlets and Ajax?

Related

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

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.

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);
});

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...

Avoiding html in servlet

I'm on a jsp page and I am doing an ajax call to a servlet which in return provides full html code to be displayed on page. It works fine but looks cluttered in servlet file to have multiple printWriter.write(...) lines with html code in it. It becomes hard to maintain as I have to create a large html code via servlet. Is there any other proper/better way to do this? I have cmobination of write html lines and logic in servlet and it will be hard to separate them.
The ajax call in jsp page:
$.ajax({
type: 'POST',
url: 'myServlet',
data: requestData,
dataType: "text",
}).done(function(responseData) {
$(divId).html(responseData);
});
Some code from servlet class:
.....
String username = user.getName();
if (username != null && !username.trim().isEmpty())
username = username.substring(0, username.indexOf(" "));
else
username = "";
printWriter.write("<span id=\"username_"+i+"\" style=\"display: none;\">"+ username +"</span>");
printWriter.write("<form action=\"\" method=\"post\" name=\"userClickForm_"+i +"\" id=\"userClickForm_"+i +"\">");
printWriter.write(" <input type=\"hidden\" name=\"userId\" value=\""+userId +"\"/>");
printWriter.write("</form>");
......
The main reason of mixing html code and business logic is I have to provide div id based on conditions and loop structure.
You should use some form of template or transformation technology. Since you're using jQuery and JSPs this can be either a server-side JSP or a client-side jQuery template plugin.
Early JSP MVC patterns take this form:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// read inputs
String foo = request.getParameter("foo");
// perform business logic
SomeResults results = new SomeDataSource().lookupDatabase(foo);
// place results into scope
request.setAttribute("results", results);
// dispatch to JSP to render results
request.getRequestDispatcher("result.jsp")
.forward(request, response);
}
This approach can be used with an AJAX call.
Alternatively, you can respond with JSON or XML data and parse this in the JavaScript, then use a JavaScript template engine to do something similar to the logic performed in the JSP.
You can avoid that by using MVC framework like STRUTS or SPRING.
Use xml rather than html on servlet and on jsp use success attribute of ajax call using jquery.... In my case its working, bt i have used type as 'GET'.
$.ajax({
url: ,
data: ,
type: ,
dataType: 'xml',
async: true,
success:function(xmlDoc)
{
var message = xmlDoc.getElementsByTagName("message");
message = message[0].firstChild.data;
}
});
And in Servlet use::
res.getWriter().write("<response><message>abcdefg</message></response>");
You should use JSP's. It will be on different pair of servlet/jsp request, not the request initiating ajax call.

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