Spring MVC returns a blank page - spring

In my project, I have a requirement to handle user POST request and fill the results into an iframe (called result_frame).
When POST request data is valid, I return a view to fill the result_frame as ModelAndView(myviewName)
When POST request data is invalid, I want to fill the result_frame with a blank page.
Is there any simple way to return a blank page without creating a separate View for it? (e.g. ModelAndView("_blank"))

Go for this code, It will return a blank page as u wish...
PrintWriter out = response.getWriter();
out.println(" ");

Related

Paginate Widget breaks layout when loaded using ajax in Typo3

There is an issue I am facing in using pagination widget with ajax. What I am doing is, that I select category and then hit an ajax request to fetch the corresponding list by loading the data in the template and returning the html like this:
<f:if condition="{articles}">
<f:then>
<f:widget.paginate objects="{articles}" as="paginatedArticles" configuration="{itemsPerPage: numberOfRecords}">
<f:for each="{paginatedArticles}" as="article">
<h2>
<f:link.action action="show" arguments="{article : article}"> {article.title}</f:link.action>
</h2>
<p>
<f:format.html>{article.description}</f:format.html>
</p>
<hr/>
</f:for>
</f:widget.paginate>
</f:then>
<f:else>
No Records Found
</f:else>
And in my controller in my ajaxMethod I am simply doing
$this->view->assign('articles', $result); so it loads up the template with my result.
But now after rendering the ajax, if I use the pagination, the view breaks. There is no styling or header or anything.
This is how it shows up when I click the next on paginate widget: http://prntscr.com/kr8vg0
Just for completeness, here is the setup.txt which I have written that calls the ajax.
// PAGE object for Ajax call:
tt_content.list.20 = CASE
tt_content.list.20 {
key.field = list_type
}
ajax = PAGE
ajax {
typeNum = 1272
config {
disableAllHeaderCode = 1
disablePrefixComment = 1
additionalHeaders {
1526302502.header = Content-Type: text/html;charset=utf-8
}
}
10 = CONTENT
10 {
table = tt_content
select {
pidInList = this
orderBy = sorting
where = (list_type IN ("articleext_list"))
}
renderObj = < tt_content.list.20
}
}
Any help would be appreciated.
The typeNum that drives (should drive) XHR requests from widgets, is added from within the Fluid extension and does not require you to add a special PAGE object.
Even if you somehow made overrides that call your specific controller action it may not be treated correctly. Usually you would never refer to a content element instance but rather a straight Extbase request bootstrapping. Among other things, because rendering the content object adds wrappers.
So you should remove this and make sure you pass a QueryResult to the pagination widget. Then override the widget template if necessary. The rest should work without having to configure TS.
EDIT:
The pagination widget itself being used in a template that is rendered via XHR means it transfers the arguments you use to load the XHR - including the custom typeNum value. The widget then creates standard links that your click like normal - and they will be a link to the "inner content" of your XHR response because the URL contains a type number.
Here's where it gets bad: you cannot remove this typeNum once it is added. So you will have to instead cause the next/prev etc. links that are clicked, to cause a new XHR request that loads the content (how you do that very much depends on your JS application so can't guide you there).
My comment about ensuring a QueryResult is not relevant unless your pages don't change and you for example always see items 1-10.
But in order to solve this I would actually recommend that you do not use the pagination widget. The main reason being you're already in an XHR context that allows you to receive arguments for your controller action and manipulate the offset and limit parts of the query from within your controller action. That means you can generate your links not to the widget but to the controller action, and for example put a CSS class on the links that should trigger XHR requests vs. those that should reload the entire page (for example to show a detail view). You avoid having to override the pagination template and you control all parameters of all links.
In fact, I would favor a controller argument for offset above using the pagination widget regardless of XHR or not. There's a long list of technical reasons why that I won't list here but suffice it to say, trading a lot of "black box" for having to create a single argument is a very reasonable and predictable-result thing to do.

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 use last insert id when redirect same form page in codeigniter

I just try to prevent re submission problem when refresh form page. so I use session flashdata() method and redirect same form page. but I want also display recent inputed data on form VIEW page. then I am try $this->db->insert_id() on my form VIEW page . but it always show 0. how can I solve it?
when you redirect the user after the successful form submission then add the parameter in the url just a exapmle with dummy code to make an idea for you
$insertedid=$this->my_model->add_info();
//your add_info() should return the inserted id
redirect("/myformcontroller/myformpage/".$this->db->insert_id());// add id in redirect url
on your myformcontroller controller's myformpage function
function myformpage() {
$insertedid=$this->url->segment(3);
if(!empty($insertedid)){
//get new added information and pass it to view
}
// your other code
}
hope it makes sense

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

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()

Resources