I have a thymeleaf index.html where I access my model attribute in a standard way:
<body>
<th:block th:text="${myModel}"></th:block>
</body>
Now I'm execute an ajax request and get another html part from my controller and set it to my index.html.
#GetMapping(value="/part")
public String getPart(Model model) {
model.addAttribute("somePart", "hello partial html!");
return "part";
}
The ajax request and the page rendering works as expected. But in this part of the html I'm not able to access my previous set ${myModel}. Is there a way to achieve that?
First sorry I am using my phone.
XHR requests don't behave the same as regular Http requests in Spring MVC. It's a little difficult to get a model attribute with Ajax because Ajax doesn't expect a view (where the model injects its data). You have 2 choices to solve your problem.
1- The easiest way, add directly your data in the response body, annotate your handler with '#ResponseBody' and return the data you want not a view name.
2- A bit twisted, your handler method should return a 'ModelAndView' but Ajax will receive the full view, when I say "full view" I mean all the text inside the view where you want to render your model.
I'll edit this answer to add some codes if you don't see what I mean.
CODE
I did the test :
#GetMapping( "/part" )
public ModelAndView getPart( Map<String, String> model ) {
model.put( "somePart", "hello partial html!" );
return new ModelAndView( "part", model ); // part = the view name
}
The view code part.html:
<div>
<h1>This is the view containing the model : ${somePart} </h1>
<p>With other information....</p>
<p>Please note that this view doesn't contain neither "head" nor "body" tags</p>
</div>
Ajax call : EDIT 2
$(function(){
var myModel = "${myModel}"; //get the value of your previous model
$.get("part",function(data){
$("div.show-part-view").html(data);//in index.html add a div tag with class="show-part-view"
$("p.my-model").html(myModel); // in the part.html view add <p class="my-model">...
});
In index.html add the <div class="show-part-view">...</div> where you want.
Result :
https://i.stack.imgur.com/iGzgg.jpg
Related
I'm trying to understand how to pass a variable from the "Client controller" field to the "Body HTML template" on a Header | Footer (sp_header_footer) record.
We have a widget embedded in a lot of pages so we just created the widget and then added it like this:
HTML Body template field:
<div>
<widget id="widget" options='{"button_color":"#F6A700", "home_page_id":"sysid"}'></widget>
</div>
What I'm trying to do is, instead of passing that object into the options, I want to make it dynamic so I can get the info of those variables dynamic via server->client->HTML
Trying to do this:
HTML Body template field:
<div>
<widget id="widget" options='{c.options.obj}'></widget>
</div>
Client Controller field:
api.controller=function() {
/* widget controller */
var c = this;
c.options.button_color = "#F6A700";
c.options.obj = {
"button_color":c.options.button_color,
"portal_page_id": c.options.sys_id
};
};
But I can't get it to receive this information inside the widget itself, and since the widget is scope blocked, I really need to retrieve that info on this record, since it's on the Global scope. Can someone help me, please?
Best regards!
He is currently working on code that has to filter the data in the table. Ajax will call the link and gets the response (json) results with answer. However, I came across a problem. I have to somehow render tables and I do not want to do this by append etc.
Can I somehow again generate views or blade file?
The default view is DefController#index but ajax use url which controller is DefController#gettabledata.
public function gettabledata($id){
return response()->json(Def::find($id)->getallmy->all());
}
You can put the part in your template corresponding to the table in a separate .blade.php file, and #include that in your main layout.
main.blade.php :
<html>
...
<body>
<div class="table-container">
#include('table')
</div>
</body>
...
And
table.blade.php:
<table>
#foreach($rows as $row)
<tr>
<td> $row->title ... </td>
</tr>
#endforeach
</table>
In this way you can use a simple jQuery $('div.table-container').load(url) and on your server just render and respond that part as an html string. return view('table', $data)
Javascript:
function refreshTable() {
$('div.table-container').fadeOut();
$('div.table-container').load(url, function() {
$('div.table-container').fadeIn();
});
}
The answer is yes, you can. Webinan certainly pointed you in the right direction. This approach is slightly different.
First things first, you need a seperate view for the table. A very basic example for the HTML markup:
<div class="table-container">
#include('partials.table') // this view will be async loaded
</div>
We start by making a call to the server with jQuery (can be done with Javascript too) using the shorthand ajax function: var $request = $.get('www.app.com/endpoint');. You can also pass along any data to your controller on the backend.
Now on the serverside, within your controller, render and return the table view:
class EndpointController extends Controller
{
/**
* Returns a rendered table view in JSON format.
*
* #param Request $request
* #return \Illuminate\Http\JsonResponse
*/
public function ajax(Request $request)
{
$html = view('partials.table', compact('view'))->render();
return response()->json(compact('html'));
}
}
If everything worked out, the done callback will be triggered. Simply grab the html variable and set it as the content of the table's container.
function renderTable() {
var $request = $.get('www.app.com/endpoint'); // make request
var $container = $('.table-container');
$container.addClass('loading'); // add loading class (optional)
$request.done(function(data) { // success
$container.html(data.html);
});
$request.always(function() {
$container.removeClass('loading');
});
}
Hope this helps!
To update and change page content without reloading the page in Laravel 5.4 i do the following:
First create the blade view in the "views" folder called "container.blade.php" it will contain the following code (in this case a select box that is rendering a list of abilities from the package Bouncer (but you can use the #foreach on any Laravel collection you like):
<select>
{{ $abilityList = Bouncer::role()::where('name','admin')->first()->getAbilities()->pluck('name') }}
#foreach ( $abilityList as $ab )
<option value="{{ $ab }}">{{ $ab }}</option>
#endforeach
</select>
Add this to you main blade file (e.g. home.blade.php) making sure to use a div with an id you can reference:
<div id="abilityListContainer">
#include('container')
</div>
Now on your main blade file (e.g. home.blade.php) add a button that will trigger the function that will communicate with the Laravel controller:
<input type="button" value="reload abilities" onClick="reloadAbilities()"></input>
Then add the javascript for this function, this loads the generated html into your div container (note the "/updateAbility" route next to ".get" - this is a Laravel route which we will set up in the next step):
var reloadAbilities = function()
{
var $request = $.get('/updateAbility', {value: "optional_variable"}, function(result)
{
//callback function once server has complete request
$('#abilityListContainer').html(result.html);
});
}
Now we set up the Laravel route for this action, this references our controller and calls the function "updateAbilityContainer". So edit your /routes/web/php file to have the following route:
Route::get('updateAbility', array('as'=> 'updateAbility', 'uses'=>'AbilityController#updateAbilityContainer'));
Finally in app/Http/Controllers make the file "abilityController.php" (you can also use "php artisan make:controller abilityController"). Now add this function to process the changes, generate the html and return it to the javascript function (note you may also have to use the namespaces as well):
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
class AbilityController extends Controller
{
public function updateAbilityContainer()
{
// use this if you need to retrieve your variable
$request = Input::get('value');
//render and return the 'container' blade view
$html = view('container', compact('view'))->render();
return response()->json(compact('html'));
}
}
Thats it, your blade "container" will now reload when you click the button and any changes to the collection you are rendering should update without reloading the page.
Hopefully this fills in some blanks left in the other answers. I hope it works for you.
I am working on application in AngularJs
Here is my code :
HTML
<div ng-controller="MainController as main" class="containerWrap">
..
..
..
<p ng-bind-html="parseMsg(msg)"></p>
..
..
The parseMsg function passes the msg filled by the user to the controller JS defined as follows :
this.parseMsg=function(msg){
...
...
if(msg['subtype']==FILES_UPLOADING){
$scope.showUploadOptions=true;
var per=parseInt(msg['text']);
if(per==100)
msg['text']='<div ng-if="showUploadOptions"><img ng-src="logo.png" ng-click="main.cancelFileUpload(chat,msg_id)"/></div>';
return $sce.trustAsHtml(msg['text']);
}
...
...
...
};
Chat and msg_id being passed to the main.cancelFileUpload are stored previously as:
$scope.chat = (object)
$scope.msg_id =(object)
this.cancelFileUpload=function(chat,msg_id){
alert("Cancel clicked ");
delete this.retryUploadFiles[msg_id];
delete chat.msgs[msg_id];
};
What I am trying to do is cancel the file upload being sent during the server request using a click on an image.
This ng-click is not responding. It doesn't give an error but doesn't function properly either.
Can anyone help identify the issues?
Thanks!
ngBindHtml don't compile your HTML. So, all angular directives from your dynamic HTML(ng-if, ng-src, ng-click, etc..) will not work.
To really compile your html you can use $compile service like that:
$compile(html)($scope)
But it's not a true way for angular. If you want to modify DOM structure - you need to use directives. In your case you can include that html to template itself instead of add it dynamically:
<div ng-show="showYourHtml">
<img ng-src="logo.png"
ng-click="main.cancelFileUpload(chat,msg_id)"/>
</div>
And your controler:
...
if(conditions){
$scope.showYourHtml = true;
}
...
I am using the Ember Timetree code (Timetree) and I think it is great. I am a newbie to Ember and D3 so jumping into the Timetree code made my head hurt.
I am trying to add functionality so that if a user clicks a button on the page, the timetree will reload with different data. I have been trying for a while but nothing seems to work.
Here is what I have:
Ember template for the timetree:
<script type="text/x-handlebars" data-template-name="index">
<div class="example">
{{view Ember.Timetree.TimetreeView contentBinding="App.ApiData" selectionBinding="selectedEvents" rangeBinding="eventsRange_example2"}}
</div>
</script>
HTML that defines the timetree div:
<div id="app"></div>
HTML for the button the user clicks:
<button type="button" onclick="loadNewTimetree()">Reload</button>
Javascript for the function to reload the timetree:
function loadNewTimetree() {
var newJsonData = .... Get the JSON data
// Replace the existing JSON data with the newJsonData and re-draw the timeline - how?
}
What is the piece I am missing that links the updated JSON to timetree?
Thanks.
Marshall
I found the answer.
First, I added a viewName="mmView" tag to my Template:
<script type="text/x-handlebars" data-template-name="index">
<div class="example">
{{view Custom.Timetree.TimetreeView viewName="mmView" contentBinding="App.ApiData" selectionBinding="selectedEvents" rangeBinding="eventsRange_example2"}}
</div>
</script>
I found the core of the answer here. So I updated my javascript function:
function loadNewTimetree() {
var newJsonData = .... Get the JSON data
// View.views returns a hashtable. Key is the id, value if the View.
var views = Ember.View.views;
for (var nextKey in views) {
var nextView = views[nextKey];
// The 'viewName' is set in the template and needs to be unique for each timeline.
if (nextView.viewName && nextView.viewName == 'mmView')
{
nextView.reloadWithNewData(newJsonData );
}
}
}
Then I added a function in my View to handle the updated JSON:
Custom.Timetree.TimetreeView = Ember.Timetree.TimetreeView.extend(
{
... Other attributes,
reloadWithNewData:function (newTimelineJson)
{
// Need to clear out the svg contents before adding the new content
// or else you get strange behavior.
var thisSvg = this.get('svg');
thisSvg.text('');
this.set('content', newTimelineJson);
this.didInsertElement();
}
});
So when I call the loadNewTimetree() function, it updates the timeline with the new JSON.
The issue may be that you are not doing things the Ember way - which is very different but awesome. In Ember the button would typically be defined as
<button {{action 'loadNewTimeTree'}}>Reload</button>
and then in your view or controller one would have an action handler that would loadNewTimeTree. Typically by loading the data into an ember model.
App.IndexView = Ember.View.extend({
actions: {
loadNewTimeTree: function () {
var newJsonData = .... //Get the JSON data or more typical
this.get('controller.model').reload(); //typically JSON handled by RESTAdapter
}
}
});
If you want to learn the ember way which may be challenging I recommend studying their website
This is my jsp page (which is a modal page to another jsp page ) which contains a table, a form, a javascript and ajax .
<%# include file="/WEB-INF/includes/taglibs.jsp" %>
<script type="text/javascript"
src="${pageContext.request.contextPath}/ajax/prototype.js"></script>
<script type="text/javascript" xml:space="preserve">
function invoke(form, event, container) {
var params = Form.serialize(form, {submit:event});
new Ajax.Updater(container, form.action, {method:'post', parameters:params});
}
</script>
<display:table name="actionBean.currentAidApplicantYear.comments" id="result" class="maui">
<display:column property="lastUpdatedBy" title="Last Updated By" sortable="true"/>
<display:column property="lastUpdatedTimestamp" title="Last Updated Date"
format="{0,date,MM/dd/yyyy HH:mm}" sortable="true"/>
<display:column property="comment" title="Memo"/>
</display:table>
<div class="actionBar" style="margin-top: 20px; text-align: center;">
<stripes:form beanclass="${actionBean.class}" id="addMemoForm" method="POST">
<tags:labelAndValue label="Comment" name="comment" >
<stripes:textarea id="commentTextArea" name="comment.comment" cols="75"/>
</tags:labelAndValue>
<stripes:submit name="saveCommentAjax" value="Add Memo"
onclick="invoke(this.form, this.name, 'result');"/>
<stripes:hidden name="id" />
</stripes:form>
</div>
And this is part of the action bean which extends another class which in turn implements ActionBean, ValidationErrorHandler
Public class CommentsTab extends AbstractAidApplicantTab {
private AidApplicantYearComment comment;
public AidApplicantYearComment getComment() {
return comment;
}
public void setComment(AidApplicantYearComment comment) {
this.comment = comment;
}
public Resolution saveCommentAjax(){
String result = String.valueOf(comment.getComment());
comment.save();//build up the comment object
//by this time the comment object will save the string comment, user who updates it and a //time stamp. Those are the three variables that are displayed on the jsp table.
return new StreamingResolution("text/html",new StringReader(result));}
//here instead of returning just a string “result” I prefer to return a comment object or //the three values I wanted to display on a table. How can I do that?
When the submit button is clicked I use an ajax to call an action bean’s method to do some operation and the function returns a streaming resolution (StreamingResolution("text/html",new StringReader(result));). Once I get the response I wanted to refresh the table without refreshing the page. However, in order to do that I have to get an object (a comment object) from the response not a text (or may be an array of Strings which might contain the values of the object)
Any help would be appreciated. Thank you
Use a JavaScriptResolution, or (better IMHO),
transform your Comment object into a JSON String (using one of the myriads of free Java JSON encoders available),
return that JSON String as a StreamingResolution
use the native JSON functions in the browser (if you target recent browsers) or a JS library containing a JSON parsing function to transform the JSON string into a JavaScript object.