auto refresh jsp page when data changes - ajax

I have a JSP page which shows items included in an Array (Just a very simple list).
In the background the Array might change i.e. adds a new Item or remove one.
How can I auto refresh the page when the Array changes?

There are 2 ways that are most popular to perform such operation
pool a method that would send 1 or 0 to see if you refresh the page or not
keep asking for that data array and populate it through javascript
Option 1
create a .jsp page and call it, for example, updateList.jsp
add a single method that will check if there is more data to be filled and output 1 or 0 like: out.println(1)
in your page, and using jQuery to simplify things
$.get("updateList.jsp", function(data) {
if(data !== null && data.length > 0 && data === 1) {
// refresh this page
document.location = document.location.href;
}
});
Option 2
create a .jsp page and call it, for example, data.jsp
add a single method that will output a JSON string containing all data you need to populate the list
in your page, and using jQuery and JsRender to simplify things
$.get("updateList.jsp", function(data) {
if(data !== null && data.length > 0) {
$("#my-list").html(
$("#my-template").render(data);
);
}
});
and in your HTML you will have:
<ul id="my-list"></ul>
<script id="my-template" type="text/x-jsrender">
{{for items}}
<li>{{:name}}</li>
{{/for}}
</script>
assuming your JSON would be something like:
item: [
{ name: "Name A" },
{ name: "Name B" },
{ name: "Name C" },
]

Once the JSP has been executed, the HTML code that it has generated has been sent to the browser, and there is no connection between the browser and the JSP anymore. If you want to refresh some part of the page, you need to poll the server using AJAX, or use WebSockets to maintain a connection between the page and the server.

To refresh page silently use AJAX. Below are some examples
Example 1
Example 2
Google Search

Related

How to get content with ajax from an admin page to all content pages?

I want to get content using ajax from an admin page and append it to all content pages on right hand side.
I have this script:
$.ajax({
url: '/Quicklinks-Content-Admin',
type: 'GET',
success: function(data) {
var quicklinks_list = [];
$('.content-inner .blogentries ul li').each(function (i, v) {
v = $(v);
quicklinks_list.push({
text: $('.blogBody a', v).text().trim(),
href: $('.blogBody a', v).attr("href"),
bg: $(v).find('.sws-inline-content img').attr('src')
});
console.log(i);
console.log(quicklinks_list[i].text);
console.log(quicklinks_list[i].href);
console.log(quicklinks_list[i].bg);
$(".quicklinks-inner").append('<div class="right-quicklink ql' + i + '"><div class="quicklink-inner"><div class="quicklink-title">' + quicklinks_list[i].text + '</div><div class="background-cover"></div></div></div>');
$('.ql'+ i +' .background-cover').css("background-image", 'url("' + quicklinks_list[i].bg + '")');
$(".quicklink-title a").html(function(index, old) {
return old.replace(/(\b\w+)$/, '<span class="lastWord">$1</span>');
});
});
}
});
With this script I extract the content from a blog list from "/Quicklinks-Content-Admin" page which is a link in two variable (text and href) and one more variable for the image. After this I want to insert the content from variables to all content pages.
Actually, that script insert the content just for that admin page, instead to put it on every single page.
Why does it happen and how to solve the problem ?
AJAX is just a procedure for sending data from/to the current webpage to a back-end PHP (or aspx etc) file.
If the transmitted data should be remembered (for example, to update other pages), then you can store it in a database and refactor the other pages to read from the database for data when constructing each of those pages.
If you require the AJAX data to be added to other areas on the same page as the AJAX routine, for example in sidebar sections that are $.load()ed when the page is constructed, just use javascript to update those areas. Or, use javascript to call another $.load() of the data into that div.
Regardless how you do it, you will either use javascript to update an area on the page you are on, or you will store the data on the server (usually using a database, but you can also use a server-side file) and make the other PHP pages read that stored information when building their pages.

Ajax populated fields on Symfony2 (category populates sub category)

I want to populate a sub category when I choose a category from a select box.
I followed this (and many many other things on the Internet for days), but I feel like it is not meant to be used with Ajax, thus not using dynamic forms like I want it to be.
Any idea how I can do this ?
Thanks.
You should write a controller, which will process your ajax requests (i.e. response with categories json). Then you should write a JS code onto your form page, which will request this controller action, process response and update your selectbox
I.e you have a controller with route name categories_ajax_path which reponse a JSON like
[
{'label':'some category 1','id':1,'group':'group 1'},
{'label':'some category 2','id':2,'group':'group 2'},
{'label':'some category 3','id':3,'group':'group 1'}
]
Then add script to the page like this
<script>
$.getJSON('{{ path('categories_ajax_path') }}', function (data) {
var opt_groups = {};
$.each(data, function (i, value) {
if (!(value.season in opt_groups))
opt_groups[value.group] = [];
var opt = $('<option/>');
opt.val(value.id);
opt.text(value.title);
opt_groups[value.group].push(opt);
});
for (var group in opt_groups) {
if (!opt_groups.hasOwnProperty(group)) continue;
var $opt_group = $("<optgroup/>", {'label': group});
opt_groups[season].forEach (function ($item){
$opt_group.append($item);
});
$('#category_list').append($opt_group);
}
})
</script>
The problem is that ajax populated forms might not pass symfony builtin validations (because this is not the choices symfony expect), so you need additional tweaks

Grails Render Partial Template to Div

I have a form page where the user selects a filter and a table on the bottom of the page updates. Each line in the table has a hyperlink in column one that associates a line item to an item in the database. I am not using GORM.
I need to be able to send the current filters to the controller via AJAX (functioning). Then I need to render a partial template (to a div) that loads the data created by a query based on the client's request parameters.
GSP:
....
<button onClick="generate_table()" class="pure-button">Generate Table</button>
...
<div id="selection_table">This should load with data</div>
...
JS:
//Link for AJAX
var url = "${g.createLink(action:'generate_table', controller: "statusReports")}";
//The actual call
$.getJSON(url, {
period: JSON.stringify($("#period").val()),
...
...
}, function(data) {
$('#selection_table').empty();
}).done(function(data) {
//I need to load the template at this point?
})
Controller:
def generate_table(){
def table_data = statusReportsService.generate_titles(params)
// Table data is already a map
// What do I need to render here? The template is named _selectionTable.gsp and should use table_data to generate html.
}
Partial:
I still haven't written the code for this yet. For now it is just some random text to see if I can even load the template when I press the button
In your controller:
render(template: 'selectionTable', model: table_data)
In your GSP/HTML you need to use $.get and use the following:
$('#selection_table').html(data)
That should do the trick!

how to show a response in Razor view

my index view displays the IEnumberable inside an html table. with the links like edit and delete. delete links is create like below.
#* #Html.ActionLink("Delete", "Delete", new { id= SomeId })*#
Inside the controlelr action methods i am calling a service that gives me delete functionality.
CustomResponseObject resp = someService.DeleteSomething(id);
Now this CustomResponseObject has a bool indicating success or failure. and a string mentioned which business rule was negated if any. I want to propagate this message to the Razor in order to show an alert box.
what will be an ideal solution in this case. ?
I would make an ajax call and than display the message depending on the result as you indicated you wanted display the message in an alert box.
$.get("~/Delete", { id: someId }).done(function(data) {
var result = data.IsSuccess ? "success" : "failure";
alert("Your operation was a " + result);
});
Sorry I just noticed you wanted to have it available in Razor. In this case I would add a field to your Model. Than in the Razor view you can access it.
As for displaying it maybe have your JS pick up on the hidden field created using
Html.HiddenFor(m => m.IsSuccess)

dynamicly fill table using zpt and ajax as update

I'm creating a webproject in pyramid where I'd like to update a table every few secondes. I already decided to use ajax, but I'm stuck on something.
On the client side I'm using the following code:
function update()
{
var variable = 'variable ';
$.ajax({
type: "POST",
url: "/diagnose_voorstel_get_data/${DosierID}",
dataType: "text",
data: variable ,
success: function (msg) {
alert(JSON.stringify(msg));
},
error: function(){
alert(msg + 'error');
}
});
}
Pyramid side:
#view_config(route_name='diagnose_voorstel_get_data', xhr=True, renderer='string')
def diagnose_voorstel_get_data(request):
dosierid = request.matchdict['dosierid']
dosieridsplit = dosierid.split
Diagnoses = DBSession.query(Diagnose).filter(and_(Diagnose.code_arg == str(dosieridsplit[0]), Diagnose.year_registr == str(dosieridsplit[1]), Diagnose.period_registr == str(dosieridsplit[2]), Diagnose.staynum == str(dosieridsplit[3]), Diagnose.order_spec == str(dosieridsplit[4])))
return {'Diagnoses ' : Diagnoses }
Now I want to put this data inside a table with zpt using the tal:repeat statement.
I know how to use put this data in the table when the page loads, but I don't know how to combine this with ajax.
Can anny1 help me with this problem ? thanks in adance.
You can do just about anything with AJAX, what do you mean "there's no possibility"? Things become much cleaner once you clearly see what runs where and in what order - as Martijn Pieters points out, there's no ZPT in the browser and there's no AJAX on the server, so the title of the question does not make much sense.
Some of the options are:
clent sends an AJAX request, server does its server-side stuff, in the AJAX call success handler the client reloads the whole page using something like window.location.search='ts=' + some_timestamp_to_invalidate_cache. The whole page will reload with the new data - although it works almost exactly like a normal form submit, not much sense using AJAX like this at all.
client sends an AJAX request, server returns an HTML fragment rendered with ZPT which client then appends to some element on your page in the AJAX success handler:
function update()
{
var variable = 'variable ';
$.post("/diagnose_voorstel_get_data/${DosierID}")
.done(function (data) {'
$('#mytable tbody').append(data);
});
}
client sends an AJAX request, server returns a JSON object which you then render on the client using one of the client-side templating engines. This probably only make sense if you render your whole application on the client and the server provides all data as JSON.

Resources