Spring MVC Ajax updating DIV - ajax

Okay...I am coming from C# MVC using partial views/ajax, etc...
Here's what I have: 1 main page with a target ID that renders the default information using a page include.
What I want to do is onclick of a button target the original ID and render a different page as the include. Kind of like RenderPartials in C# MVC.
Can Spring (using Maven) MVC do this or is there a way to go about this that is strait forward?
Thanks,

You don't need to implement partial views just have an empty div and on click of a button make an ajax request get the content and update the div. something like below.
function button_onclick() {
var params = {}; //put parameter if any
$.ajax({
headers: {
Accept : "text/plain; charset=utf-8","Content-Type": "text/plain; charset=utf-8"},
url: "/controller",
method:"GET",
data:params,
success:function(data, textStatus,response) {
var text = response.responseText;
if (text == "") {
return;
}
$( "#DIV_ID" ).text(text);
},
error: function(response) {
alert(response);
// terminate the script
}
});
}

Related

How to display ajax success response inside div with javascript

I am writing one ajax call and collect the response from controller. I want to show that response(jsp) to one particular div. Please help me, how to put response div to current page div.Below is the code:
function openSocietyTab(divName, parentTabName, subTabName)
{
debugger;
var i;
var x = document.getElementById(divName);
var parentTempId = parentTabName;
var tempId = subTabName;
$.ajax({
type : "GET",
url : "/ApartmentAdda/"+parentTempId+"/"+tempId,
data : {x:tempId},
timeout : 100000,
success : function(x) {
debugger;
console.log("SUCCESS: ", x);
// here i want to display x into divName div.(x is the jsp view which i am getting from controller)
},
error : function(e) {
console.log("ERROR: ", e);
}
});
}
I am calling this javascript function on button click:
<button class="w3-bar-item w3-button dropbtnInr" onclick="openSocietyTab('tabToOpen','societyService','houseTab')">Houses</button><br>
and tabToOpen is the div on which I want to open ajax response jsp.
There are many ways, but since you only want to display a certain div then I'd suggest you to use the hidden class to hide and show the div.
For example if the div has id="tabToOpen" and you are using jQuery then it would be:
$(#tabToOpen).addClass('hidden');
$(#tabToOpen).removeClass('hidden');
If you are not using jQuery then try:
var theInfoDiv = document.getElementsById('tabToOpen');
theInfoDiv.classList.add('hidden');
theInfoDiv.classList.remove('hidden');

Play framework render HTML & values on same page via ajax

I'm using ajax within the play (scala) framework to run some code after a click event occurs on a page. I want to return the results of that code execution on the same page.
EDIT: the goal of this is to display some rows from the database, along with form elements to fill out to update cells of the databse, all without reloading/or going to a new page
Is there a way to pass html + (scala) values into
Ok(...).as(HTML)
to display without directing to new a page?
I know Ok can take things like:
Ok(<h1>it works</h1>).as(HTML)
but I can't figure out how to combine that with scala values as well. Is there a smarter way to do this?
EDIT: the ajax looks like this:
var ajaxCall = function() {
var ajaxCallBack = {
success : onSuccess,
error : onError
}
jsRoutes.controllers.Application.scrape().ajax(ajaxCallBack);
};
var onSuccess = function(data) {
$("#results").append(data);
}
var onError = function(error) {
alert(error);
}
For sure you can. You can use TWIRL templates:
Create a template "views/Application/contacts.scala.html
#(users: List[User])
<h1>Users</h1>
<ul>
#for(user <- users) {
<li>#user.name</li>
}
</ul>
in the controller:
Ok(views.html.Application.contacts(users))

How to present partial view in jQuery dialog without navigating to another page

I have two controllers, A and B. A is responsible for representing some data in a grid view. Assume I have a button called "ShowInfo" which brings additional info about the selected record. And to retrieve the info about the selected record is the job of controller B.
The info is so little that it'd take just a tiny place in the corner if I navigate to another view. So I thought I'd rather bring that info inside a jQuery dialog without navigating to anywhere. But I'm a bit confused as to how to do it.
Here's the action method in controller B that is responsible for providing that info in a partial view.
public class BController:Controller{
public ActionResult GetInfo(int recordID){
RecordInfo info=RecordsRepository.GetRecordInfoById(recordID);
return PartialView(viewName:"RecordInfo",model:info);
}
}
I don't know, maybe the action method needs to different. Maybe I should return JSON instead of Partial view, but anyway, how do I do that?
You can use the jquery .get or .load methods. For example, to replace the contents of <div id="SomeElement"></div> with the partial view returned by GetInfo()
$('#ShowInfo').click(function() {
var url = '#Url.Action("GetInfo", "B")';
var ID = someValue; // the value to pass to the GetInfo method
$.get(url, { recordID: ID }, function(data) {
$('#someElement').html(data);
});
});
You can use Jquery ajax to achieve this.
Wrtire jquery ajax on the view page and call the partial view action from ajax.
receive the result in html format and replace it in the dialog box.
Put following code on main view page(ShowInfo button page)
$(document).ready(function(){
$("#ShowInfo").on("click",function(){ ///give id to showinfo button and attr data-id is record id
var id=$(this).attr("data-id");
$.ajax({
type: "POST",
url: "B/GetInfo",
data: JSON.stringify({ recordID: id }),
dataType: "html",
success: function (html)
{
////put the html response in dialog box
}
});
})
});

modifying an element in master page based on action in content page

I have a Link element in the Master Page. This element is initially invisible.
Upon a certain action in one of the content page, I need to make that Link element visible.
I am looking into ways of how this could be done. Can I do it from my Controller method or will I have to do it via ajax?
To manipulate the UI in mvc you need to use javascript. If your "certain action" are involved with the server I think you need to use ajax:
$.ajax({
url: "yourController/yourAction",
dataType: 'json',
success: function(json){
var domEl = document.getElementById('theIdOfyourLink');
if(json.show){
domEl.style.display = 'block';
}else{
domEl.style.display = 'none';
}
}
});
If you action are only involved with the client you can use only javascript. At the end you can playing with css to make visible or not your link:
var yourfun = function(show){
var domEl = document.getElementById('theIdOfyourLink');
if(show){
domEl.style.display = 'block';
}else{
domEl.style.display = 'none';
}
}
One option would be to use TempData or ViewData.
Your 'certain action' in your controller could be like
public ActionResult MyCertainAction()
{
TempData["ShowLink"] = true;
}
Then, you masterpage could have the following
#if (TempData["ShowLink"] != null && (bool)TempData["ShowLink"])
{
My link
}
Find control on master pages
Found this, might help.
From your code behind you can just find the control, cast it, and manipulate it.
Panel pnlWelcome2 = this.Master.FindControl("pnlWelcome") as Panel;

Spring MVC: Auto-save functionality (jQuery, Ajax...)

I'd like to implement a "auto-save" functionality on my page. I don't really know how to start though. I got one object (with a list of tasks). I'd like to submit the form every 20 seconds, so the users won't lose their data. It doesn't have to be exactly like that. After every submit the submit-button should be disabled as long as there are no changes.
I'm using Spring MVC. I did some research but I'm not an expert in jQuery, Spring... So it's all pretty complicated for me. A tip, or a working example would help me a lot.
It's a pretty complex form (a timesheet). There are +/- 50 textboxes on one page (minimum, depends on the number of tasks available)
Thanks.
I don't know what spring mvc is, but in ASP.NET MVC I would do the following:
I assume all your data is in a form, you give the form an ID, then post it:
$(function () {
var timer = 0;
$(this).mousemove(function(e){
timer = 0;
});
$(this).keypress(function() {
timer = 0;
});
window.setInterval(function () {
timer++;
if (timer == 20) {
$('#form').submit(function() {
});
}
}, 1000);
});
Checks for mousemove, keypress, if this isnt done in 20 seconds then it saves the form.
Edit: What you could also do maybe is, after every textbox they fill in, post the data: as followed:
http://api.jquery.com/change/
$('.textbox').change(function() {
$.ajax({
url: '/Save/Textbox',
data: 'TextBoxId=' + $(this).id + '&TextValue=' + $(this).value
});
});
In this example, you make a controller called Save, action called Textbox, you give the textbox the ID of data that it has to save, and on change (after un focussing the textbox), it posts the textbox id, and the value of the box.
then in the controller you retrieve it:
public void SaveText(string TextBoxId, string TextValue) {
// SAVE
}
Below Js script will help you to make ajax call when ever form field changes.
<script>
$(document).ready($('.form-control').change(function() {
$.ajax({
type : "post",
url : "http://localhost:8521/SpringExamples/autosave/save.htm",
cache : false,
data : $('#employeeForm').serialize(),
success : function(response) {
var obj = JSON.parse(response);
$("#alert").text(JSON.stringify(obj));
$("#alert").addClass("alert-success");
},
error : function() {
alert('Error while request..');
}
});
}));
</script>

Resources