How to use ng-repeat with an ajax request with DataTables? - ajax

Let's say I'd like to load a dataTable dynamically, but instead of using normal ajax function within datatable, I'd like to load it through Angular, use ng-repeat to generate the tr elements and then apply DataTables. Would that be possible? In broad terms, how could I do that?
I've got the ajax/ng-repeat working already like this:
angular.module('myApp', ['ngResource', 'ui.bootstrap'])
.factory('ProjectsService', ['$resource', function($resource) {
return $resource('/customers');
}])
.controller('AdminCustomersCtrl', ['ProjectsService', '$scope', function(ProjectsService, $scope) {
$scope.projects = ProjectsService.query();
}]);
The reason I'd like to do this is that all elements (data in the table) would be binded, so whenever the user edit an entry in the table, the change would be acknowledged immediately (visually) and also saved to the REST server. Each entry in the table would correspond to a mongo db document. So if anyone has any ideas of how to achieve this differently, I'd love suggestions.

Related

How to show wpDataTables results inside popup using AJAX

I am using wpdatatables to display data.
I have added MySQL Query in backend, and that query has 2 dynamic parameter like
SELECT some fields
FROM tbl1 tb1
JOIN tbl2 tb2
ON some conditions
JOIN tbl3 tb3
ON some conditions
WHERE DATE(Date) BETWEEN '%VAR1%' AND '%VAR2%';
wpdatatables Generate shortcode like [wpdatatable id=some_id] ,
I have create 2 date-picker for Start Date and End Date on Frontend.
Now I have to pass dynamic parameter like [wpdatatable id=some_id var1="strt_dt" var2="end_dt"]
So to get strt_dt and end_dt, I have call AJAX and pass parameters.
My problem is I am showing all this data inside popup.
I mean when user clicks on See Report Button
one popup will be open. Data also Displayed correctly. But it showing without wpdatatables Layout.
It is not Considering wpdatatables JS or CSS
Here is my AJAX Callback Function :
public function get_datatable_data() {
echo do_shortcode('[wpdatatable id=some_id var1="'.$_POST['strt_dt'].'" var2="'.$_POST['end_dt'].'"]');
wp_die();
}
Here is Code in which I am appending data :
var params = {"strt_dt":strt_dt,"end_dt":end_dt,action:"get_datatable_data"}
jQuery.post(ajaxurl,params,function(data){
if(data){
jQuery(".some class").empty().append(data);
}else{
jQuery(".some class").empty().append("No data Found");
}
This would have been possible if you are using normal datatable where you can re-initalize datatable on ajax success by using following code.
$("#div").dataTable().fnDestroy()
$("#div").dataTable();
But if you are using Plugin then there is no direct way to achive this, one possible solution is to create a normal page with datatable shortcode in it and then in you ajax callback you call that page in iframe.
for eg: you create page www.mysite.com/datatable - this page will have the actual shortcode
public function get_datatable_data() { ?>
<iframe src="www.mysite.com/datatable" height="200px"></iframe>
<?php
wp_die();
}
this will allow datatable to get initalize in iframe.

Insert a view using JS?

Is it possible to insert a view using javascript?
I wish to perform an ajax call, get the data, then insert a view in to a page and provide the data from the ajax call to that view?
Is this possible?
Yes you can use the render method on a view. Like so;
$view = View::make('your.view')->render();
And then return the html (which is the output) from your controller method by returning the data stored in $view.
If you need to add any data to the view just add the second parameter to the view make.
alternatively you can do this,
set the route for pages you want to call.
e.g.,
Route::get('callajax','PagesController#showAjax');
and then in PagesController#showAjax you return the view.
e.g.,
public function showAjax()
{
return View::make('ajaxpages');
}
and then in ajax call you code this
$.ajax({
url:'callajax',
});

How do I auto fill field values in a section of a form that is loaded via ajax in Laravel 4?

I have a section of a form that dynamically loads different sets of fields based on the user's selection in a control. I'm using a javascript event handler to detect when the selection changes, and using AJAX (with HTML payload) to pull in the proper set of fields.
I would like to be able to use Laravel's Form::getValueAttribute() method to automatically fill in the form fields' values in both the static and dynamic form parts. However, the partial view that is loaded by my AJAX call does not have the same instance of the Form class as the view with my main Form, so I can't simply call getValueAttribute() in the partial.
My thought is to make the AJAX call a POST, and serialize the necessary data (a subset of Input::old() or the model data depending whether the page is loaded as the result of validation errors, or an UPDATE request) to send along with the POST so that the HTML fragment I get back has the values set properly.
Is this the best way to get what I want? If so, does Laravel have any tools to help with the serialization of form data? If not, what might be a better approach?
I've found an approach I like better. When the view is loaded normally I use AJAX as usual to load the partial. But when the view is loaded for a validation post-back or for editing, I use Laravel's Views' nest method to nest the partial view containing the proper fields directly into the response. The partial then has access to all the Input and error data I need. The user is still able to change the field set as usual but I put up a confirm prompt for them if they have already set some values in a field set they previously selected. If they decide to proceed anyway, the field set is cleared and a new field set is brought in via AJAX as usual.
My code looks something like this:
Controller:
public function newThing() {
if ( Request::session()->has('errors') ) {
// this is a validation post-back
return View::make('thing')
->nest('fields', 'fields_partial');
} else {
// just a normal unfilled form
return View::make('thing');
}
}
public function editThing() {
return View::make('thing')
->nest('fields', 'fields_partial');
}
View: thing.blade.php (just a snip of it)
...
<form>
...
<select id="picker">...</select>
<div class="sub-fields">
{{ isset($fields) ? $fields : '' }}
</div>
...
</form>
...
<script>
$('#picker').change(function() {
// if any .sub-fields inputs have been changed, get confirmation from the user
// if user confirms, do ajax stuff to replace .sub-fields contents with new field set
// otherwise cancel the change
});
</script>

Calling a function on a table of async populted data in Meteor

I am using Meteor and the jquery data table library.
I have a table that I am loading meteor/handlebars using something like this:
<table>
{{each x}}
// code to insert rows of data
{{/each}}
</table>
I need to call this on the table once it has been fully populated with data to turn it into a sortable table:
$('#tableID').dataTable();
It works when I call it from the console once the DOM is fully loaded and the data is in there, but using Template.rendered() doesn't work, nor does listening for changes with .observe since the data is loaded before that particular view is rendered.
Where can I run this code to ensure that the data is fully loaded, and if there are updates to the data in the table that it will run again?
I found a way of doing it which seems to work after I split the individual rows into templates - will update as I continue to debug it (and this is certainly not ideal).
Template.individualRow.rendered = function() {
if (!$('#tableID').hasClass('initialized')) {
$('#tableID').not('.initialized').addClass('initialized').dataTable();
};
};
It beats me, but I can suggest a way to work around:
Do not use handlbars' helper, and observe the data, when the data changed, re-render the template manually, like this:
<table id="tableID"></table>
<template name="yourTemplate">
{{#each this}}
<tr>....</tr>
{{/each}}
</template>
var query = ...
query.observe({
added: function () {
manuallyRender();
},
changed: function () {
manuallyRender();
},
...
});
function manuallyRender() {
// don't need Meteor.render here, because you don't need it to be reactive.
var frag = $(Template.yourTemplate(query.fetch()));
$('#tableID').empty().append(frag).dataTable();
}
It should work, but maybe not the best way, any thoughts?
Actually, I think meteor has a long way to go...

JSON data for jQuery dataTable in web2py

I am trying to load json data from web2py controller to jQuery dataTable via AJAX.
But only blank dataTable is rendered (with desired formatting, search box, etc.)
Can somebody pl. point out into my code as to where I have a mistake.
Data is not displayed (as returned by "get_data" method).
I have made sure that the database tables have been populated.
Controller
def show_data():
return dict()
def get_data():
custdata = db.executesql(qry, as_dict=True)
return custdata
For testing purpose, I returned response.json(custdata) in a separate method & validated the same on "jsonlint.com".
It is valid json.
View (show_data.html)
{{extend 'layout.html'}}
$(document).ready(function() {
var oTable = $('.smarttable').dataTable( {
"sScrollY": "200px",
"sAjaxSource": "{{=URL('MIS','get_data.json')}}",
"sDom": "frtiS",
"bDeferRender": true
} );
} );
Lastly, html table tags are defined for a table with class="smarttable"
Your get_data function should return a dictionary, like this:
def get_data():
custdata = db.executesql(qry, as_dict=True)
return dict(data=custdata)
In web2py, a view is only called if the controller action returns a dictionary -- otherwise, the controller output is simply returned to the client as is (and as is, custdata has not yet been converted to JSON).
When you call the URL /MIS/get_data.json, the .json extension tells web2py to look for a /views/MIS/get_data.json view file to use for rendering the JSON. If it doesn't find that view file, it will trying using /views/generic.json, though it will only use generic.json for local requests, unless you override that by specifying response.generic_patterns=['json'].
As an alternative to using a view to render the JSON, you could also do:
def get_data():
custdata = db.executesql(qry, as_dict=True)
return response.json(custdata)
EDIT: The jQuery DataTables plugin requires the JSON to include some special parameters, so you'll have to add those before returning the JSON. To make things easier, you might consider using PowerTable (a web2py plugin for DataTables), or the jqGrid widget included with web2py's plugin_wiki (the widget can be used on any web page, not just wiki pages).
you have to have the "key" values in the "dictionary" that you give for return .
iTotalRecords,iTotalDisplayRecords,sEcho and aaData. you can find the explanations in http://datatables.net/usage/server-side

Resources