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.
Related
I should like to use functional from this file https://ahunter.ru/js/min/ahunter_suggest.js
The documentation says that
1. import files
<head>
...
<script src="path_to_scripts/jquery.min.js"></script>
<script src="path_to_scripts/ahunter_suggest.js"></script>
...
</head>
Add id for input field
<div>
<input id="js-AddressField" placeholder="Введите адрес">
</div>
Add script
<script>
var options = { id : 'js-AddressField' };
AhunterSuggest.Address.Solid( options );
</script>
I added file to my project directory and added link into index.html, but i can't call
AhunterSuggest.Address.Solid( options ); in one of my controller.
How will do it right?
In your AngularJS controller, u have a method for initialising the controller right? If so, you have to call 3rd party library initialiser (3rd code in your message)
Make sure to call this, after dom is ready and angularJS controller initiated.
Your angular controller before (atm)
init() {
this.xxx()
}
Angular Controller after: (should be sth like this)
init() {
this.xxx()
this.initialiseAHunterSuggest()
}
initialiseAHunterSuggest() {
var options = { id : 'js-AddressField' }
AhunterSuggest.Address.Solid( options )
}
I have the following AJAX script running in my Django template:
function create_table() {
$.ajax({
method: "GET",
url: "/api/data/",
success: function(data){
console.log('button clicked')
console.log(data)
//$('#table').html('<div class="test">' + data['Name'] +'</div>');
//$('#table').load('table_to_load.html');
},
error: function(error_data){
console.log("errorrr")
console.log(error_data)
}
})
}
document.getElementById("create_table").onclick = function() {
create_table();
return false;
}
The purpose of this script is to create a HTML table upon button click populated by dictionary data fetched by the AJAX call.
The AJAX call collects the data correctly, however, I don't know how to go about inserting the table.
Should I write the table HTML in pure Javascript/jQuery inside the AJAX call? Or maybe load a pre-prepared HTML (how do I reference its directory inside the call?)?
My preferred method though would be to write the template for the table in Django's template tag language and somehow reference in it the data fetched by AJAX. Something like:
<table>
<tr>
<th>dictionary key</th>
<th>dictionary value</th>
</tr>
{% for key, value in dictionary.items %}
<tr>
<td>{{ key }}</td>
<td>
{{ value }}
</td>
</tr>
{% endfor %}
</table>
But I am not sure if it's possible.
You can do it either way, but you seem like you are trying to do in in 1/2 of both ways.
You can use ajax to make a call and get back some json data, and then use that json object to build the html string and use jquery to insert that html at the correct point in your page - nothing wrong with that way imo, though I personally am not a fan of hand stitching together html statements (mostly because for complicated pages it gets hard to design them and debug them this way, but for small pieces its OK).
An alternative is to have jquery call django view (via a url you have defined), and have that django view make the database call and use a template that is already in your project as a html doc, and then render that template and data just like you would any other django page. That view would return an httpresponse containing html, and then jquery would just insert that html into the page as before.
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
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