how can I redirect in .jsp while working with Ajax - ajax

I am developing application using Ajax and jsp.
My index.jsp page has HTML code for Login and some Ajax code in javascript. Ajax will call my another CheckLogin.jsp page
CheckLogin.jsp page checks on server for valid username and password. It returns "success" if it's valid otherwise will return message stating "username or password is not valid."
Now, when username and passwrod is valid, instead of success, I want to redirect the page to "Home.jsp" what should I do?
I am new to jsp. I appreciate your help on this.

JSP code gets run once on the server before it goes to the client, so JSP/JSTL cannot do a redirect following the success or otherwise of an AJAX call (without a full page refresh - which obviates the use of AJAX). You should to do the redirect with Javascript:
if (success) {
var successUrl = "Home.jsp"; // might be a good idea to return this URL in the successful AJAX call
window.location.href = successUrl;
}
On successful AJAX call/validation, the browser window will reload with the new URL (effectively a redirect).

Since I don't see your code, you can integrate this somewhere inside your validation :
<%
pageContext.forward("logged.jsp");
%>

function Edit() {
var allVals = $('#NEWFORMCampaignID').val();
if (allVals > 0) {
window.location = '/SMS/PrepareSMS?id='+allVals;
}
else
alert("Invalid campaign to Edit")
}
In order to redirect using Button click and pass some parameters, you can call the Controller Path(#RequestMapping(value="/SMS/PrepareSMS")) and then handle it there..

Related

Spring-Boot: Redirect and Refresh model and page

I have a spring-boot application, with theyemleaf. I repeatedly update the page, and redirect it to the same page, so i expect that the elements of the page get updated:
#GetMapping("/suggested-events/vote/{eventId}")
public String voteForEvents(Model model,
#PathVariable("eventId") Long eventId,
#RequestParam(value = "message", required = false) String message ) {
log.info("The message is: "+message);
SuggestedEvent event = suggestedEventService.findSuggestedEventById(eventId);
ArrayList<SuggestedEvent> events = suggestedEventService.findSuggestedEventsByArea(event.getArea());
model.addAttribute("mainEvent",event);
model.addAttribute("events",events);
model.addAttribute("message",message);
return "/suggested-event/vote";
}
and when a button get pushed in the view it triggers the below post method:
#PostMapping("/suggested-events/vote")
public String voteForASuggestedEvent(RedirectAttributes redirectAttributes){
log.info("You have made a vote");
redirectAttributes.addAttribute("message", "Success");
return "redirect:/suggested-events/vote/1";
}
This second controller method, performs an operation an makes a message, and redirects it to the first method. So, it successfully redirected to the first method and it logs
log.info("The message is: "+message);
but it does not refresh my page, and i do not get the message as model?
When i redirect to the first method, i expect it adds the message to my models:
model.addAttribute("message",message);
But it does not added to my page
and when a button get pushed in the view it triggers the below post
method:
It sounds like this trigger is using AJAX, rather than a form submit. Doing so would match the symptoms you describe.
If you POST to /suggested-events/vote using AJAX, the server will return a 302, and the browser will follow it. However, the response for that 302 is still the result of an AJAX call. You have access to it in your success callback, but the browser isn't going to render it for you.
but it does not refresh my page
If a 302 doesn't cause your page to re-render, this also suggests you're using AJAX.
If you actually use a form submit instead, the browser will re-render using the markup returned by the successful redirect.
This can be verified by using the following two buttons in your vote.html:
<form action="http://localhost:8080/suggested-events/vote" method="POST">
<input type="submit" text="Submit" />
</form>
<button onclick="postmessage();" >Button</button>
<script>
function postmessage() {
$.ajax({
method: 'POST',
data: {},
url: 'http://localhost:8080/suggested-events/vote'
});
}
</script>
The first button will work as expected, and the second button matches the symptoms you describe.
If you are already using a form, please update the question with it (or better yet, the entire Thymeleaf template).
I had the same problem as OP described and Mike's explanation brought me in the right direction.
I am reading a db-table and populating it with thymeleaf using th:each. I wanted to add a javascript-confirmation before deleting an item. Sending an ajax GET without an event-listener and reloading with location.reload(true) didn't reach the #GetMapping("/delete/{id}") in the controller.
This SO-thread gave me the answer to the ajax-call.
<a class="btn btn-danger" href="#" th:onclick="|confirmDeletion('${u.id}')|"></a>
<script th:inline="javascript">
function confirmDeletion(id) {
if (confirm("Delete this id? " + id)) {
var http = new XMLHttpRequest();
http.open("GET", "/delete/" + id, true);
http.addEventListener("readystatechange", function() {
if (http.readyState === 4 && http.status === 200) {
window.location.reload(true);
}
});
http.send();
}
}
</script>
there are many ways to redirect page in Spring, but be sure if the model attribute off message its passing correctly to FrontEnd or passing like parameter to another handler , you can see this document : http://javainsimpleway.com/spring-mvc-redirecting-model-attributes-from-one-controller-to-other-controller/ , hope this is useful !!

Displaying error messages in jsp without reloading page

I have a program using jsp and servlets that checks the database for an email address. First the jsp page sends the email to the doPost method of the servlet, then the servlet checks the database, if email exists I use request.setAttribute set a success message and then forward it to the same jsp page, if it doesn't exist it forwards an error message.
The problem i am facing is that it refreshes the jsp page, whereas when I used php for another program i was able to display just by echo without refreshing the entire page.
You can use JQuery Ajax request to do this:
Servlet:
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("good email or not?");
Jsp:
$('#emailButton').click(function() {
$.post('mySevlet', function(responseText) {
if (responseText == 'good'){
$('#statusDiv').text('you are good to go.');
}else{
$('#statusDiv').text('Stop Righ there!');
}
});
});

Django / Closure: How to validate AJAX form via AJAX?

I'm using Django and Google's Closure javascript library, and I want to do some form processing via AJAX.
Currently, I have a button on the page that says "Add score." When you click it, it fires off a goog.net.Xhrio request to load another URL with a form on it and display the contents in a little pop up box, via a call to loadForm().
loadForm = function(formId) {
var form = goog.dom.getElement(formId);
goog.style.setElementShown(goog.dom.getElement('popup-box'), true);
goog.net.XhrIo.send(form.action, displayForm, form.method);
}
displayForm = function(e) {
goog.dom.getElement('popup-box').innerHTML = e.target.getResponseText();
}
The Django form that gets loaded is a very basic model form, with a simple "score" attribute that gets validated against a number range. Here's the code I have to process the form submission:
def Score(request):
obj = ScoreModel.get(pk=request.POST['obj_id'])
form = ScoreForm(request.POST, instance=obj)
if form.is_valid():
form.save()
messages.success(request, 'Score saved!')
return shortcuts.redirect('index')
else:
context_vars = {'score': score, 'form': quarter_form}
shortcuts.render_to_response(
'score_form.html', context_vars,
context_instance=context.RequestContext(request))
This would all work fine if the form to enter the score itself was just displayed on the page, but because it is an AJAX popup, it doesn't work properly. If I just do a simple form submission (via HTML submit button), it works fine if the data is valid. But if the data isn't valid, instead of displaying the form with errors in the popup, it just loads only the text that would've been displayed in the popup - the form with errors - in the main browser window rather than in the popup.
Conversely, if I submit the form via my loadForm() JS method above, it works perfectly fine if the form is invalid (and displays the invalid form in the popup box), but doesn't work if the form is valid (because the main index page ends up getting displayed in my popup's innerHTML).
I can't seem to figure out how to get the code to work in both scenarios. So, how can I have my cake and eat it to? :)
This is kind of a strange issue, so if I didn't explain it well enough, let me know and I'll try to clarify. Thanks in advance.
I got it to work. The basic trick was, if the form submission was successful, instead of returning a redirect I returned a basic response object with a redirect status code and the URL to redirect to. Then I modified my displayForm() to look for that and redirect if it was found.
Here's the modified code from the Score() function:
if form.is_valid():
form.save()
messages.success(request, 'Score saved!')
redirect = shortcuts.redirect('index')
return http.HttpResponse(content=redirect['Location'],
status=redirect.status_code)
And the modified displayForm():
var displayForm = function(e) {
var responseText = e.target.getResponseText();
if (e.target.getStatus() == 302) {
// If this was a redirect form submission, the response text will be the URL
// to redirect to.
window.location.href = responseText;
} else {
// Regular form submission. Show the response text.
goog.dom.getElement('popup-box').innerHTML = responseText;
}
};

Parital view show login page with fullsite if session out after computer left idle for long time

I have created an asp.net mvc razor application, in which I load a partial view in a div, which can be accessed after login.
<% using (Ajax.BeginForm("Showproducts", "Home", new AjaxOptions {
UpdateTargetId = "resdiv", OnBegin = "fstart()", OnSuccess = "fend()"
}, new { id = "_myform" }))
{ %>
.....
<% } %>
When a user leaves their computer for a long time (which makes the session time out automatically) and then clicks the submit button, the resdiv is filled with the full site with the login panel. I want to show the full site with login panel NOT in the resdiv. Is there any way to avoid this behavior?
Is there any way to avoid this behavior?
Yes, there is a way. I would recommend you reading the following blog post in which Phil Haack illustrates a very nice technique allowing you to override the Forms Authentication Module for AJAX requests and be able to send a 401 status code instead of redirecting to the login page.
Then on the client side you could use a global AJAX handler where you could test the status code and if it is 401 redirect to the logon page.
For example once you have installed the AspNetHaack NuGet you could add the following global error handler to your view:
<script type="text/javascript">
$(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
if (jqXHR.status == 401) {
// not authenticated => redirect to login page:
window.location.href = '#FormsAuthentication.LoginUrl';
}
});
</script>

create a nested jQuery post in another post callback?

since I'm new in jquery, can you tell me how to redirect a page to another action method ?
I develop a MVC web application. I use jquery post method to do some validation, and when it return true, it will be redirect page to another one.
My problem is..when when I redirect page using window.location, it's works well in IE (IE 9). but didn't work on firefox & chrome.
So, I try to using jquery post method to redirect page from action method in my controller. I call redirect post method in a jquery post call back.
it is my code :
$.post(posturl, formData, function (result) {
if (result == 'True') {
$.post("/Controller/RedirectMethod", {_Action: 'Index', _Controller: 'Home'}, null);
}
else
alert('failed');
}
);
and this is my RedirectMethod :
[HttpPost]
public ActionResult RedirectMethod(string _Action, string _Controller)
{
return RedirectToAction(_Action, _Controller);
}
so how I should create a nested post in another post callback ?
or there is another way to redirect page ?
thanks,
You won't be able to do a RedirectToAction inside an Ajax request.
If you need the web page to change to a different location inside the Ajax response, use window.location as Ben suggested.
One thing to bear in mind is that you'll need to remove the 'HttpPost' action filter.

Resources