Displaying error messages in jsp without reloading page - validation

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

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

show success message on same page after adding recording without reloadin the site in cakephp 2.x

I want to add a show sucess message using :-
session->flash(); ?> in view and added the message in controller :-
Session->setFlash("Record has been saved successfully."); ?>
But I donot want to reload the whole page.
I am just inserting the new record using ajax.. and refreshing the div having list of all record.
session->flash(); ?> this works if i reload the whole page.
how can I show message once the record is saved using ajax.
Solutions (i recommend the first one):
Create AJAX method in controller that return 200 code with JSON/HTML record's data or any other error code if sth goes wrong. Then in js do:
$.ajax({ ... }).done(function( data ) {
// Success, show the record and message
$('#flash').text('Success!').show();
// ...
}).error( function() {
// Error
$('#flash').text('Error!').show();
});
Refresh the records list by calling ajax method and return not only the view with list of all records, but also a flash message (in the same view). Then show it or move using javascript.

How to return jsp page in spring mvc 3 ajax call

I have a main page with header, footer, left panel and main content. I want to dynamically change main content on click of left panel. For this I am using ajax call, ajax will call controller and controller will return jsp which I will replace in main content.
But the problem I am facing is that I am getting JSP properly if I am using purely html coding but if I use spring form it is not working.
Do I need to declared taglib in all jsp or only in Dashboard jsp.
If I declare taglib in all child jsp then it not working and I do not declare then form:input do not render in to html
Can we return jsp in ajax call to replace with main content because here it says only #ResponseBody (JSON) can be used in ajax call.
I am using ajax call because I don't want to reload all my header, footer and left panel because they will always remain same.
Ajax code
<script type="text/javascript">
$(".ldMainContent").click(function(){
var actionName = this.id;
actionName = "${pageContext.request.contextPath}/sadmin/forward/"+actionName;
$.ajax({
url:actionName,
type:"POST",
data:"URL",
success:function(result){
$("#mainContent").html(result);
}
});
});
</script>
I am using bootstrap in design
The content can be loaded using jQuery's load method.
The code will be
$(".ldMainContent").click(function(){
var actionName = this.id;
actionName = "${pageContext.request.contextPath}/sadmin/forward/"+actionName;
$("#mainContent").load(actionName);
})
In your controller don't have #ResponseBody it is used to return object as JSON or XML. The controller should return a view for the JSP page which should only have the content that you want inside the mainContent.
Do I need to declared taglib in all jsp or only in Dashboard jsp.
Yes you have to declare the taglibs which ever jsp file you are using the tags.

ASP.NET MVC: How to display success confirmation message after server-side processing

I have a requirement to display a message confirming a successful database update in an ASP.NET MVC application. Currently the application only shows messages (using a ValidationSummary helper) when an error occurs. On a successful operation, the application currently redirects to a suitable point in the navigation.
Goals are:
Display the confirmation message in an appropriate way
Minimise user actions required to proceed after reading message
Avoid an extra post / round-trip to display the message
Minimise development effort and risk inserting a message at multiple points in the application
My preference would be some sort of tool-tip type message display near the submit button and then a mechanism for removing the message and proceeding with the existing redirection after success.
That seems to suggest an Ajax call rather than the existing HTTP POST to submit the form. How would I go about this?
I Would use TempData["key"]
This is like ViewData["key"] however the data persists for the next HttpRequest and is disposed automatically by asp.net after this
So you can do this.
Controller Action
[HttpPost]
public ActionResult SomePostAction(SomeViewModel vm)
{
if(ModelState.IsValid) // Is User Input Valid?
{
try
{
CommitData();
TempData["UserMessage"] = new MessageVM() { CssClassName = "alert-sucess", Title = "Success!", Message = "Operation Done." };
return RedirectToAction("Success");
}
catch(Exception e)
{
TempData["UserMessage"] = new MessageVM() { CssClassName = "alert-error", Title = "Error!", Message = "Operation Failed." };
return RedirectToAction("Error");
}
}
return View(vm); // Return View Model with model state errors
}
_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
</head>
<body>
#if(TempData["UserMessage"] != null)
{
var message = (MessageVM)TempData["UserMessage"];
<div class="alert #message.CssClassName">
<strong>#message.Title</strong>
#message.Message
</div>
}
#RenderBody()
</body>
</html>
More Info: http://www.devcurry.com/2012/05/what-is-aspnet-mvc-tempdata.html
On a successful operation ,you just store the success message description into ViewBag
like as
ViewBag.successMessage="Success"
then in view check the ViewBag value is null or not? through javascript ,if not null show the message in Div
if('#ViewBag.successMessage'!="")
{
$('#divSuccessMessage').show();
}
else
{
$('#divSuccessMessage').hide();
}
default in page load hide the div
the following links might help you (posting links as it would require better explanation):
http://msdn.microsoft.com/en-us/magazine/ff797575.aspx
http://ofps.oreilly.com/titles/9781449320317/ch_AJAX.html
As others mentioned, TempData is one of the most straight forward options to use. Its main drawback in regular ASP.NET in my opinion is that it uses the session storage in to store its contents. This means that you'll have extra work getting it to function on a web farm, or that you need to turn on sessions in the first place.
TempData is a string based dictionary you can put anything in it, and by default get it out only once on any later request. Before calling RedirectToAction() you set your message and on the next request you check for messages and display them. By retrieving the messages they are automatically deleted at the end of the request.
As an alternative you could use cookies for transporting the message between the two requests. Essentially you could either roll your own solution, or implement a custom ITempDataProvider which transports the contents of TempData via cookies. Given that the messages are short, the performance impact is minimal. Note that you need to properly secure cookies.
I was facing the same problem you did and created a solution for it called FlashMessage. It's available on NuGet. Usage is simple: you simply queue a message before you call RedirectToAction() as follows:
FlashMessage.Confirmation("Your message");
return RedirectToAction("AdminUsers", "Admin");
In your view you include the following statement to render any previously queued messages:
#Html.RenderFlashMessages()

how can I redirect in .jsp while working with 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..

Resources