JQuery DataTable resets on button click - javascript

I am using jQuery DataTables on a site that features the regular searchbox and some preset buttons that sort the table by column when pressed. The code does indeed sort the table when the button resets, but it immediately resets within 1/2 second. Here is my code:
//CATEGORY BUTTONS
$("#Term").on('click', function (event) {
dataTable.column(2).search('Term').draw();
});
I've searched around and looked at many forums. This should be correct, but the result always instantly resets the form. I've removed the search box functionality to see if that was interfering and causing the issue, but the issue remained. It just blinks the results up really fast and then resets it all to showing the entire list again. Could this be a thing with Internet Explorer (this machine has no access to any other browsers)?
Here is the full code:
$(document).ready(function () {
//USES API FOR DYNAMIC SEARCHING
//RENDERS TABLE
var dataTable = $("#videos").DataTable({
"paging": false,
bjQueryUI: true,
ajax: {
url: "/api/videos",
dataSrc: ""
},
columns: [
{
width: "70%",
data: "title",
render: function (data, type, video) {
var videoTitle = video.title.toUpperCase();
return "<VideoItem><a href='" + "../" + video.url + "'>" + "<spacerTop>" + videoTitle + "</spacerTop></a></VideoItem>";
}
},
{
width: "10%",
visible: false,
data: "description",
render: function (data) {
return data;
}
},
{
width: "10%",
visible: false,
data: "categoryName",
render: function (data) {
return data;
}
},
{
width: "10%",
visible: false,
data: "meta",
render: function (data) {
return data;
}
},
{
width: "10%",
visible: false,
data: "date",
render: function (data) {
return data;
}
},
{
width: "10%",
visible: false,
data: "categoryID",
render: function (data) {
return data;
}
}
]
});
//CONTROLS DELETE BUTTON ACTION
$("#videos").on("click", ".js-delete", function () {
var button = $(this);
bootbox.confirm("Are your sure you want to delete this video?", function (result) {
if (result) {
$.ajax({
url: "/api/videos/" + button.attr("data-video-id"),
method: "DELETE",
success: function () {
button.parents("tr").remove();
}
});
}
});
});
//MAKES SEARCH BOX ON TOP INTERACT WITH DATATABLE
$(".search-box-input").keyup(function () {
dataTable.search(this.value).draw();
});
//CATEGORY BUTTONS
$("#Term").on('click', function (event) {
dataTable.column(2).search('Term').draw();
});
});

Related

Selectize.js - how to know that an item selected came from "Add Item" instead of the preloaded options

I have this code.
$customer = $(".customer").selectize({
valueField: 'builder',
labelField: 'builder',
searchField: 'builder',
openOnFocus: true,
createOnBlur: true,
maxItems: 1,
create: function (input) {
newOption = true;
return {
builder: input,
value: input,
text: input,
};
},
render: {
option: function (item) {
return (
"<div class='selectize-item'>" +item.builder+ "</div>"
);
},
},
load: function (query, callback) {
if (!query.length) {
return callback();
}
$.ajax({
url: "/api/xxx/xxx",
type: "GET",
dataType: "json",
data: {...},
error: function () {
callback();
},
success: function (res) {
callback(res);
},
});
},
});
I've used selectize to a dropdown that allows users to add their own option. I believe this can be done through the create method.
My question here is how can I know that the user has added a new option instead of selecting the options that were pre-loaded. I am planning that if the user has added a new option I will make my variable newOption into true, while if the user has selected to the options that were pre-loaded, newOption will be false.
When I say "pre-loaded", this is an option that has been loaded through Ajax. You can see it on my load method that the dropdown options are loaded through Ajax.
Any help is greatly appreciated!

Use ajax to populate select2 only on open

I'm using the following code to fetch options from a database and populate a select2 on open. It works pretty well, but as soon as I start typing in the select2 search input box it also searches via the same ajax function. How can I just populate every time it opens, but then leave it there as long as it's opened?
Also since I'm using it to create tags I lost the ability to auto-select the new tag when I attached the ajax part, so instead of typing and pressing enter to add a tag, it's now stuck in search-land and I have to click on the newly created tag manually if I want it to be selected.
Any ideas?
function formatMenu (data) {
if (!data.id) { return data.text; }
var $data = $(
'<nobr>' + data.text + '</nobr>'
);
return $data;
};
$('select').select2({
templateSelection: formatMenu,
dropdownCssClass: 'select2-menu',
dropdownParent: $('#parent'),
placeholder: '-',
tags: true,
allowClear: true,
ajax: {
url: "?ajax=get_data,
dataType: 'json',
delay: 250,
data: function (params) {
return {
searchTerm: params.term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: false
},
sorter: function(data) {
return data.sort(function (a, b) {
a = a.text.toLowerCase();
b = b.text.toLowerCase();
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
return 0;
});
},
createTag: function (params) {
return {
id: params.term,
text: params.term
}
}
});

$.deferred does not work as expected

on some button's click event I'm calling function a() which contains below mentioned Ajax call, in the success I'm using $.Deferred. It works perfectly fine on very first click of the button but when I click a button second, third, fourth... or nth time it does not work as expected (It does not go inside of confirmation function at all). what I'm doing wrong. Thank you in advance.
$.ajax({
type: "GET",
url: "some url",
data: {
parameters
},
success: function (result) {
//result is an Array object. for example **result:Array[3]**, further expand result will be like this **result[0]:Array[19], result[1]:Array[39], result[2]:Array[15]**
var defer = $.Deferred();
function confirmation(result) {
if (result.length > 1) {
$('#field' + questionID).append('<div id=dialog></div>');
$("#dialog").append('<div id=grid></div>');
$("#dialog").kendoDialog({
modal: true,
visible: false,
draggable: true,
closable: false,
title: "Please Select One Submission",
maxWidth: 500,
//maxHeight:300,
animation: {
open: {
effects: "slideIn:down fadeIn",
duration: 500
},
close: {
effects: "slide:up fadeOut",
duration: 500
}
},
actions: [
{ text: 'OK', primary: true, action: onOK }
]
});
$("#grid").kendoGrid({
dataSource: {
data: result,
schema: {
data: function (result) {
return $.map(result, function (item) {
return $.map(item, function (innerData) {
for (var i = 0; i < displayFields.length; i++) {
if (displayFields[i] == innerData.FieldIDString) {
return {
EntryGroupID: innerData.EntryGroupID,
FieldTextString: innerData.FieldTextString,
EntryValue: innerData.EntryValue
}
}
}
});
});
}
},
pageSize: 2,
group: { field: "EntryGroupID" }
},
filterable: {
mode: "row"
},
pageable: {
refresh: true,
},
noRecords: {
template: "No records to display"
},
groupable:false,
//scrollable: true,
selectable: true,
columns: [{
field: "EntryGroupID",
title: "Submissions",
filterable: {
cell: {
operator: "contains"
}
}
}, {
field: "FieldTextString",
title: "Questions",
filterable: {
cell: {
operator: "contains"
}
}
}, {
field: "EntryValue",
title: "Answers",
filterable: {
cell: {
operator: "contains"
}
}
}]
});
var wnd = $("#dialog").data("kendoDialog");
wnd.wrapper.find('.k-dialog-title').css('background', CIMSFields.backgroundColour).css('color', CIMSFields.textColour).css('width','100%').css('text-align','center');
wnd.open().center(true);
//in this function i'm waiting for user response which they will choose one array object based on this value **Confirmation** function will get the data.
function onOK(e) {
var data = [];
var grid = $("#grid").data("kendoGrid");
var selectedItem = grid.dataItem(grid.select());
if (selectedItem != null) {
$.map(result, function (item) {
if (selectedItem.EntryGroupID == item[0].EntryGroupID) {
data.push(item);
defer.resolve(data);
}
});
}
else {
defer.resolve(data);
}
wnd.close();
}
}
else
{
defer.resolve(result);
}
return defer.promise();
}
alert(defer.state());
confirmation(result).then(function (data) {
//it never reach here except first time
alert(defer.state());
alert(data);// data is the user selected value from the grid.
})
}
});
If result is an array, .empty is not an Array property or method. $.Deferred() is not necessary, $.ajax() returns a jQuery promise object.
You can check .length of expected array, or property of expected object at .then() chained to a() call. Also, chain .fail() to log and handle errors that could possibly occur.
function a(/* parameters */) {
// note, we are `return` ing `jQuery.ajax()` call,
// which returns a jQuery promise object
return $.ajax({type: "GET", url: "some url", data: {parameters}})
}
a()
.then(function(result, textStatus, jqxhr) {
console.log(result.length, jqxhr.state());
if (result.hasOwnProperty("empty")) { console.log(result.empty); }
else { console.log("result does not have property \"empty\""); };
})
// log, handle errors here
.fail(function(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown, jqxhr.state());
});
found my answer here
basically my need was I have to wait for user response in the function before proceeding further. Thank you all who took time to respond my question. I appreciate your time and effort. Most importantly I'm not using deferred at all now.

How to load data from ajax to zabuto calendar plugin?

As title, I tried load data from ajax to zabuto calendar, but seem it's not working, ref of zabuto calendar http://zabuto.com/dev/calendar/examples/show_data.html. And i want to use this function load data when click nav prev month or next month. (use two action action and action_nav). This is snipped code
<script>
$(document).ready(function () {
function load_data() {
var list = '';
$.ajax({
type: "POST",
url: "../BUS/WebService.asmx/LOAD_DATA",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (data) {
list = $.parseJSON(data.d);
console.log(list);
}
});
return list;
}
function myNavFunction(id) {
//code in here
}
function myDateFunction(id) {
//code in here
}
$("#my_calendar").zabuto_calendar({
data: load_data(),
action: function () {
return myDateFunction(this.id);
},
action_nav: function () {
return myNavFunction(this.id);
}
});
});
</script>
When i test this, data not show, the data from ajax as
{ "date": "2016-06-01", "title": 2, "badge": true },{ "date": "2016-06-04", "title": 1, "badge": true },{ "date": "2016-06-10", "title": 1, "badge": true }
Thank you so much.
Try the following: you need to place the calendar function in the success function of the ajax call because ajax is asynchronous
$(document).ready(function () {
function load_data() {
$.ajax({
type: "POST",
url: "../BUS/WebService.asmx/LOAD_DATA",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (data) {
var list = $.parseJSON(data.d);
$("#my_calendar").zabuto_calendar({
data: list;
});
},
error: function (data) {
console.log(data.d);
}
});
}
load_data();
});
I solved the issue by the code as below. It works well in window's browser but not in a mobile browser.
function initZabuto(id, events, month){
$('#zabuto_parent').empty().append("<div id='"+id+"'></div>");
$("#"+id).zabuto_calendar({
year:moment(month).format("YYYY"),
month:moment(month).format("MM"),
language:"cn",
data: events,
action: function () {
zabutoDayClick(this.id);
},
action_nav: function () {
zabutoMonthChange(this.id);
}
});
}
This is the code I used to refresh Zabuto calendar after a modal. The problem with other options is that upon refresh, Zabuto would create a new batch of modals appended to the current body. This solutions clears all those "old" modals and opens room for the new. Key area is the success section of the modal update ajax.
$(document).ready(function () {
$("#date-popover").popover({html: true, trigger: "manual"});
$("#date-popover").hide();
$("#date-popover").click(function (e) {
$(this).hide();
});
load_calendar();
});
function load_calendar() {
$("#my-calendar").zabuto_calendar({
show_next: 1,
action: function () {
return myDateFunction(this.id, false);
},
ajax: {
url: "calendar-info.php",
modal: true
},
});
}
function myDateFunction(id, fromModal) {
$("#date-popover").hide();
if (fromModal) {
$("#" + id + "_modal").modal("hide");
var date = $("#" + id).data("date");
var optradio = $("#" + id + "_modal").find("input[name='optradio']:checked").val();
$.ajax("calendar-update.php?status="+optradio+"&date="+date, {
success: function(data) {
$(".modal").remove();
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
$("#my-calendar").empty();
load_calendar();
},
error: function() {
alert("Problem!");
}
});
}
var hasEvent = $("#" + id).data("hasEvent");
if (hasEvent && !fromModal) {
return false;
}
return true;
}

Select2 - infinite scroll not loading next page with remote data

I am using Select2 4.0.1, I have used ajax to populate the result based on users input, but whenever I search for anything select2 lists first page result, but consecutive pages were not loading, also request is made for 2nd page on scroll. seems to be I am missing something.
$multiselect = $(element).select2({
closeOnSelect: false,
multiple: true,
placeholder: 'Assign a new tag',
tags: true,
tokenSeparators: [","],
ajax: {
url: '/search_url',
dataType: 'json',
type: 'GET',
delay: 250,
data: function(params) {
return {
search: params.term,
page: params.page
};
},
processResults: function(data, params) {
var more, new_data;
params.page = params.page || 1;
more = {
more: (params.page * 20) < data.total_count
};
new_data = [];
data.items.forEach(function(i, item) {
new_data.push({
id: i.name,
text: i.name
});
});
return {
pagination: more,
results: new_data
};
},
cache: true
}
})
Any help is much appreciated.Thnx:)
This is the code I got working last week. I am using a different transport on my end, but that shouldn't make a difference. I was having the same issue as you regarding the lack of paging working while scrolling. My issue ended up being that I didn't have the proper {'pagination':{'more':true}} format in my processResults function. The only thing I can see that may work for you is to "fix" the page count in the data function vs. the processResults function.
When you scroll to the bottom of your list, do you see the "Loading more results..." label? Have you attempted to hard code the more value to true while debugging?
this.$(".select2").select2({
'ajax': {
'transport': function (params, success, failure) {
var page = (params.data && params.data.page) || 1;
app.do('entity:list:search',{'types':['locations'],'branch':branch,'limit':100,'page':page,'term':params.data.term})
.done(function(locations) {
success({'results':locations,'more':(locations.length>=100)});
});
}
, 'delay': 250
, 'data':function (params) {
var query = {
'term': params.term
, 'page': params.page || 1
};
return query;
}
, 'processResults': function (data) {
return {
'results': data.results
, 'pagination': {
'more': data.more
}
};
}
}
, 'templateResult': that.formatResult
, 'templateSelection': that.formatSelection
, 'escapeMarkup': function(m) { return m; }
});

Categories