DataTable().ajax.reload() not defined - datatables

I have the following code under DT v1.10:
var oTable = $('#items')
.dataTable({
sDom: "<'row'<'col-md-4'l><'col-md-6'f>r>t<'row'<'col-md-4'i><'col-md-7'p>>",
oLanguage: {
sLengthMenu: "_MENU_ per page"
},
ajax: "/items",
bProcessing: true,
bServerSide: true,
aoColumnDefs: [
{
aTargets: [-1],
bSearchable: false,
bSortable: false
}
]
})
.on('click', '.btn-danger', function (e) {
if (confirm('Are you sure you want to delete SKU "' + $(this).data('sku') + '"?')) {
$.getJSON($(this).attr('href'), function (data) {
if ('success' in data) {
oTable.ajax.reload(null, false);
}
});
}
event.stopPropagation();
return false;
});
When the server responds with success, it tries to call the line oTable.ajax.reload(null, false); but I always get the error Uncaught TypeError: Cannot read property 'reload' of undefined
What am I doing wrong here?

You're using old API: $().dataTable() (v1.9 and earlier) which is still available in DataTables v1.10. The old API returns jQuery object, so you should use .api() in order to use DataTable API methods:
oTable.api().ajax.reload();
The new API is returned via: $().DataTable()
Datatables FAQ
Q.: I get an error message stating that an API method is not available
A.: Very likely you are using a jQuery object rather than a DataTables API instance. The form $().dataTable() will return a jQuery object, while $().DataTable() returns a DataTables API instance. Please see the API documentation for further information.
API documentation
It is important to note the difference between $( selector ).DataTable() and $( selector ).dataTable(). The former returns a DataTables API instance, while the latter returns a jQueryJS object. An api() method is added to the jQuery object so you can easily access the API, but the jQuery object can be useful for manipulating the table node, as you would with any other jQuery instance (such as using addClass(), etc.).

As a follow up to phillip100's answer, you dont have to change all your old code, or change the initialization method just to use the new API. You can always get the dataTables 1.10.x API on the fly :
...
if ('success' in data) {
//oTable.ajax.reload(null, false);
$('#items').DataTable().ajax.reload(null, false);
}
...
Would be perfectly well too. jQuery dataTables check if there already is a dataTables instance of $("#items"), so there will be no redundancy.

Related

Kendo UI autocomplete dynamically loading dBdata when typing

I am writing a kendo UI autocomplete widget. The requirement is EACH TIME when I type a letter after "minLength", the dataSource need to be dynamically loaded from dB EVERYTIME. One problem is that, when the dataSource load successfully in the first time, it stops loading data.
The code snippet is:
var data;
function getDataFromDb(){
// some code to grab dummyData from dB ...
return dummyData;
}
$("#someInputText").kendoAutoComplete({
minLength: 2,
dataTextField: "someField",
dataSource: getDataFromDb(),
filter: "startswith"
});
Thanks a lot.
More details on the post. In my situation, I don't use the readOption. The data comes from another ajax call like:
var data [];
//fire this ajax call when input string length comes to 4...
$.ajax({url: "some working url", success: function(result){
var data = result;
startKendoAutoComplete();
}
});
function startKendoAutoComplete(){
if( !$.isEmptyObject(data)) // set a breakPoint, have data
{
$("#inputText").kendoAutoComplete({
minLength: 4,
dataSource : data,
...
});
}
}
Also, the ajax call will be fired when the input string length comes to 4. However, the KendoAutoComplete doesn't start working....
Thanks a lot for your sugesstion.
If you init your dataSource with an array of object, your widget will work with this array only.
The first thing you'll have to create an dataSource object and set the serverFiltering property to true. Then, if you don't specify an url where the data will be fetched, you set you own transport.read function and from there you'll be able to implement your own logic. The read function will receive the readOption which will include all the relevant information to query tour data (top / skip / filter / sort ...). The readOptions will also provide a success function that should be used to return the value:
dataSource: {
serverFiltering: true,
transport: {
read: function (readOptions) {
readOptions.success(getDataFromDb(readOptions));
}
}
},

dojo JsonRest call not working

I'm trying to call my RESTful service from dojo. All I can see from debugger is, it tries to call the service but it doen't reach there. There are no errors. I can see the 'hello' alert.
define(["dojo/store/JsonRest","dojo/domReady!"],
function(JsonRest){
alert("Hello");
var rest = new JsonRest({
target: "/my/rest/call"
});
}
);
I's following this page from dojotoolkit.
But if i call using a declare then it works.
define(["dojo/store/JsonRest","dojo/_base/declare","dojo/domReady!"],
function(JsonRest, declare){
var rest = declare(JsonRest);
var restResult = new rest({
target: "/my/rest/call"
});
}
);
What am I doing wrong here?
error messages in console:
You're not following that tutorial to the letter. The difference is that you're using define and not require. Dojo's define is used in combination with declare to create new Dojo classes. Dojo's require is used to load and use existing classes. The link below is a recommended read and in your case pay special attention to the 'Requiring modules' and 'Defining modules' parts:
https://dojotoolkit.org/documentation/tutorials/1.8/modules/
If you use require like in that tutorial, it works perfectly:
require([
'dojo/store/JsonRest',
], function(
JsonRest
) {
new JsonRest({
target: 'some/resource/'
}).get(1).then(function (item) {
alert(JSON.stringify(item));
});
});
Here's a working example on Plunker: http://plnkr.co/edit/ZhsO67BFpWB5Txqy0Zl9?p=preview

EmberJS Route to 'single' getting JSONP

I'm having trouble with EmberJS to create a single view to posts based on the ID, but not the ID of the array, I actually have a ID that comes with the json I got from Tumblr API.
So the ID is something like '54930292'.
Next I try to use this ID to do another jsonp to get the post for this id, it works if you open the api and put the id, and actually if you open the single url with the ID on it, works too, the problem is:
When, on the front page for example, I click on a link to go to the single, it returns me nothing and raise a error.
But if you refresh the page you get the content.
Don't know how to fix and appreciate some help :(
I put online the code: http://tkrp.net/tumblr_test/
The error you were getting was because the SingleRoute was being generated as an ArrayController but the json response was not an Array.
App.SingleController = Ember.ObjectController.extend({
});
Further note that the model hook is not fired when using linkTo and other helpers. This because Ember assumes that if you linked to a model, the model is assumed to be as specified, and it directly calls setupController with that model. In your case, you need to still load the individual post. I added the setupController to the route to do this.
App.SingleRoute = Ember.Route.extend({
model: function(params) {
return App.TKRPTumblr.find(params.id);
},
setupController: function(controller, id) {
App.TKRPTumblr.find(id)
.then(function(data) {
controller.set('content', data.response);
});
}
});
I changed the single post template a bit to reflect how the json response. One final change I made was to directly return the $.ajax. Ember understands jQuery promises directly, so you don't need to do any parsing.
Here is the updated jsbin.
I modified: http://jsbin.com/okezum/6/edit
Did this to "fix" the refresh single page error:
setupController: function(controller, id) {
if(typeof id === 'object'){
controller.set('content', id.response);
}else{
App.TKRPTumblr.find(id)
.then(function(data) {
controller.set('content', data.response);
});
}
}
modified the setupController, since I was getting a object when refreshing the page and a number when clicking the linkTo
Dont know if it's the best way to do that :s

Dojo FitleringSelect does not respond well after dojo store get's associated

With the code bellow I'm trying to assign a new store to a FilteringSelect that had no store associated with it.
My issue is that I get a error when clicking the FilteringSelect witch is:
*Uncaught TypeError: Object [object Object] has no method 'query' *
console.log("alternate on movement create");
storeData = new Write({url: "/account/getall", clearOnClose: true, urlPreventCache: true});
storeData.fetch({ onComplete: function () { console.log("done");} });
console.log("after new read");
dijit.byId("far_mt_accountbundle_movementtype_toAccount").store = storeData;
I'm using dojo 1.8
Thank you for any help.
It looks like you are using an ItemFileWriteStore, which is an implementation of the deprecated dojo.data API. To use an ItemFileWriteStore with a FilteringSelect, you should wrap it in a dojo/store/DataStore
require(['dojo/store/DataStore','dojo/data/ItemFileWriteStore'],function(DataStore,Write){
var writeStore = new Write({url: "/account/getall", clearOnClose: true, urlPreventCache: true});
var dataStore = new DataStore({store: writeStore});
dijit.byId('filteringSelect').set('store',dataStore);
});

xhr.post not getting JSON response

I'm trying to use Dojo to post to my server. The server is returning a JSON response (I have debugged it and know its returning a sensible value) but I'm just getting a 'Syntax error' in the Javascript console when it returns. Any ideas?
function submitStatusUpdate() {
dojo.xhr.post({
form:"statusUpdateForm",
handleAs: "json",
load: function(data){
alert('Saved with id ' + data.id);
},
error: function(err, ioArgs){
// again, ioArgs is useful, but not in simple cases
alert('An error occurred');
console.error(err); // display the error
}
});
}
I've also tried it like this
function submitStatusUpdate() {
var posted = dojo.xhr.post({
form:"statusUpdateForm",
load: function(data){
},
error: function(err, ioArgs){
// again, ioArgs is useful, but not in simple cases
console.error(err); // display the error
}
});
posted.then(function(response){
alert('returned ' + response);
});
}
But the response that gets printed out in my alert just seems to be the HTML for my entire page. I'm expecting a JSON object. I'm struggling to find a simple example that tells me how to submit a form, and then have a callback function that reads the response.
Thanks
EDIT (thanks to Richard for the guidance)
This is the working version.
<script language="Javascript">
dojo.require("dijit.form.Button");
dojo.require("dijit.form.TextBox");
dojo.require("dijit.form.CheckBox");
function sendForm(){
var form = dojo.byId("myform");
dojo.connect(form, "onsubmit", function(event){
// Stop the submit event since we want to control form submission.
dojo.stopEvent(event);
// The parameters to pass to xhrPost, the form, how to handle it, and the callbacks.
// Note that there isn't a url passed. xhrPost will extract the url to call from the form's
//'action' attribute. You could also leave off the action attribute and set the url of the xhrPost object
// either should work.
var xhrArgs = {
form: dojo.byId("myform"),
load: function(data){
// As long as the server is correctly returning JSON responses, the alert will
// print out 'Form posted. ' and then the properties and values of the JSON object returned
alert("Form posted." + data);
},
error: function(error){
// We'll 404 in the demo, but that's okay. We don't have a 'postIt' service on the
// docs server.
alert("error");
}
}
// Call the asynchronous xhrPost
alert("Form being sent...");
var deferred = dojo.xhrPost(xhrArgs);
});
}
dojo.ready(sendForm);
</script>
This is (kind of) what my form looks like. This will work anyway (my real form is much bigger). Interestingly I had to change my normal [input type="submit"...] tag into a [button...] to get it to work properly
<form method="post" id="theform" action="postIt">
<input value="Some text" name="formInput" type="text"/>
<input name="checkboxInput" type="checkbox"/>
<button id="submitButton" type="submit">Send it!</button>
</form>
A JavaScript syntax error on parsing an XMLHttpRequest reply usually indicates invalid data from the server. My favourite tool for monitoring XMLHttpRequest traffic is Firebug. It parses JSON so if there's anything wrong, you'll know immediately.
Once you've determined that the JSON data from the server is valid, have a look at the following example from the Dojo documentation. I think it does what you're trying to do.