How to set ajax global event to false when using Bloodhound - ajax

i am using typeahead for autocomplete.The following code is working fine.
var employees = new Bloodhound({
datumTokenizer: function (d) { return Bloodhound.tokenizers.whitespace(d.name); },
queryTokenizer: Bloodhound.tokenizers.whitespace,
addOnBlur: true,
remote: {
url: $url + '?name=%QUERY',
global: false,
wildcard: '%QUERY',
filter: function (response) {
return $.map(response.results, function (employee) {
return {
mark: employee.MARK,
actitle: employee.ACCOUNTTITLE,
code: employee.CODE
}
});
}
}
});
employees.initialize();
$($classname).typeahead({ highlight: true, minLength: 1, limit: 5 }, {
name: 'employees', displayKey: 'mark', source: employees.ttAdapter(), global: false
})
.on("typeahead:selected", function (obj, company1) {
//debugger;
$($retField).val(company1.actitle);
$($cField).val(company1.code);
})
.on('focusout', function (obj, company) {
//debugger;
$($classname).trigger("typeahead:first-child");
});
}
i want to set ajax global event to false.
Please help me to solve the issue

Late to the party but I figured it out. Use the transport property:
var employees = new Bloodhound({
datumTokenizer: function(d) {
return Bloodhound.tokenizers.whitespace(d.name);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
addOnBlur: true,
remote: {
url: $url + '?name=%QUERY',
global: false,
wildcard: '%QUERY',
transport: function(opts, onSuccess, onError) {
var url = opts.url.split("#")[0];
var query = opts.url.split("#")[1];
$.ajax({
url: url,
data: "search=" + query,
type: "POST",
success: onSuccess,
error: onError,
global: false
})
}
filter: function(response) {
return $.map(response.results, function(employee) {
return {
mark: employee.MARK,
actitle: employee.ACCOUNTTITLE,
code: employee.CODE
}
});
}
}
});
employees.initialize();
Based on this other stackoverflow answer:

Related

Uppy + Laravel can't upload file

Trying to use Uppy JS lib to upload file throug Laravel. Setted up simple upload form with there params:
const options = {
endpoint: '/parts/image-upload',
headers: {
'X-XSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
},
};
uppyDashboard.use(XHRUpload, options);
And on the backend I'm getting
Illuminate\Contracts\Encryption\DecryptException: The payload is invalid. in file /Users/rd/Projects/xxx/vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php on line 195
It's like Laravel trying to decrypt something what is already decrypted, anyway I'm in dead end.
You can this code
var uppy = new Uppy.Core({
// debug: (...args) => console.debug(`[Uppy] [${getTimeStamp()}]`, ...args),
// warn: (...args) => console.warn(`[Uppy] [${getTimeStamp()}]`, ...args),
// error: (...args) => console.error(`[Uppy] [${getTimeStamp()}]`, ...args),
autoProceed: true,
restrictions: {
maxFileSize: 2000000,
maxNumberOfFiles: 10,
minNumberOfFiles: 1,
allowedFileTypes: ['image/*']
}
});
uppy.use(Uppy.Dashboard, {
target: ".UppyDragDrop",
inline: true,
showLinkToFileUploadResult: false,
showProgressDetails: true,
hideCancelButton: true,
hidePauseResumeButton: true,
hideUploadButton: true,
proudlyDisplayPoweredByUppy: false,
locale: {} });
Here's how I implemented it
<script type="text/javascript">
$(document).ready(function() {
$('[id*=drag-drop-area]').each(function(){
var listing_id = $(this).attr('class');
var uppy = new Uppy.Core({
allowMultipleUploadBatches: true,
restrictions: {
maxFileSize: 100000000,
// maxNumberOfFiles: 8,
minNumberOfFiles: 1,
allowedFileTypes: ['image/*', '.jpg', '.jpeg', '.png']
}
})
.use(Uppy.Dashboard, {
inline: true,
target: "#"+$(this).attr('id')+""
})
.use(Uppy.XHRUpload, {
endpoint: 'upload',
formData: true,
bundle: true,
headers: {
'X-CSRF-Token': " {{ csrf_token() }} "
},
});
uppy.on('upload-success', (file, response) => {
response.body.data.forEach(function (item, index) {
console.log(listing_id);
var token =
$('meta[name="csrftoken"]').attr('content');
$.ajax({
url: 'attach',
type: 'POST',
data: { '_token' : token, item, listing_id},
success: function(response)
{
console.log('Updated');
},
error:function (e) {
console.log(e);
}
});
});
window.location.reload();
});
});
});
</script>
You create the endpoint which is the route name and attach at
endpoint: ""
Then you return a response which you grab and do whatever on the last section.
uppy.on('upload-success', (file, response) => {
response.body.data.forEach(function (item, index) {
console.log(listing_id);
var token =
$('meta[name="csrftoken"]').attr('content');
$.ajax({
url: 'attach',
type: 'POST',
data: { '_token' : token, item, listing_id},
success: function(response)
{
console.log('Updated');
},
error:function (e) {
console.log(e);
}
});
});
window.location.reload();
});
I hope this helps

Kndo TreeView LoadOnDemand not hitting the server

for my kendo treeview, i set load on demand to true but it is not hitting the server to load childs, because the 'children' property is set for the datasource model, even its empty.
homogeneous = new kendo.data.HierarchicalDataSource({
transport: {
read: {
type: 'POST',
contentType: "application/json; charset=utf-8",
url: obj.DataSourcesURL,
dataType: "json"
},
parameterMap: function (options) {
if (!options.Id) {
options.Id = null;
}
if (options.filter) {
options.Search = options.filter.filters[0].name;
}
else {
options.Search = '';
}
return JSON.stringify(options);
}
},
schema: {
data: "d",
errors: function (response) {
console.log(response);
console.log("errors");
},
model: {
hasChildren: "hasChild",
children:'items',
id: "Id"
}
}
});
And treeView code is
$treeView.kendoTreeView({
dataTextField: 'Description',
checkboxes: {
checkChildren: true
},
dataSource: homogeneous,
loadOnDemand: loadOnDemand,
check: function () {
var checkedNodes = [];
var treeView = $treeView.data("kendoTreeView");
getCheckedNodes(treeView.dataSource.view(), checkedNodes);
setMessage(checkedNodes.length);
},
dataBound: function (e) {
if (e !== undefined)
resetCheckedNodes(e.sender.dataItems());
},
messages: {
loading: "Laden..."
},
expand: function (e) {
var dataItem = this.dataItem(e.node);
}
});
Try to set hasChildren like this in your schema:
schema: {
data: "d",
errors: function (response) {
console.log(response);
console.log("errors");
},
model: {
hasChildren: function(e) {
return e.items && e.items.length;
},
children:'items',
id: "Id"
}
}
And also from your question I am not sure do you even get any data or it is only Children data that is not returned. Maybe you could also show how your data structure look like.

How to make the method getItem from the offlineStorage of the Kendo Datasource work with LocalForage

I need to setup my datasource to use localForage to manage my offline data storage.
The problem I'm having is that localForage is asynchronous by nature, only allowing us to use a callback or a promise to retrieve data.
This is how my code is set-up:
(function () {
'use strict';
var serviceId = 'employeeDataSource';
angular.module('app').factory(serviceId, function () {
var crudServiceBaseUrl = 'Data/Employees';
var dataSource = new kendo.data.DataSource({
type: "odata",
offlineStorage: {
getItem: function () {
localforage.getItem('employees-key').then(function (value) {
console.log(value);
return JSON.parse(value);
});
},
setItem: function (item) {
if (item.length > 0) {
localforage.setItem("employees-key", JSON.stringify(item));
}
}
},
transport: {
read: {
url: crudServiceBaseUrl + "/",
dataType: "json"
},
update: {
url: function (data) {
return crudServiceBaseUrl + "(guid'" + data.EmployeeId + "')";
}
},
create: {
url: crudServiceBaseUrl
},
destroy: {
url: function (data) {
return crudServiceBaseUrl + "(guid'" + data.EmployeeId + "')";
}
}
},
batch: false,
pageSize: 5,
serverPaging: true,
schema: {
data: function (data) {
return data.value;
},
total: function (data) {
return data['odata.count'];
},
model: {
id: "EmployeeId",
fields: {
EmployeeId: { editable: false, nullable: true },
Name: { validation: { required: true } },
Email: { validation: { required: true } },
IsManager: { type: "boolean" },
MaxHolidaysPerYear: { editable: false, type: "number", validation: { min: 0, required: true } },
HolidaysLeftThisYear: { type: "number", validation: { min: 0, required: true } }
}
}
},
error: function (e) {
if (e.xhr.responseText !== undefined) {
console.log(e.xhr.responseText);
}
}
});
dataSource.online(navigator.onLine);
$(window).on("offline", function () {
dataSource.online(false);
});
$(window).on("online", function () {
dataSource.online(true);
});
return dataSource;
});
})();
When off-line, the getItem gets called, then the setItem gets call as well with an empty array, hence the:
if (item.length > 0) {
localforage.setItem("employees-key", JSON.stringify(item));
}
When the promise finally returns the off-line data (with the correct values I expected), the Grid displays no results.
This behaviour is presumably because of the promise ?
I tried the same thing with sessionStorage and its worked perfectly... i.e.:
getItem: function () {
return JSON.parse(sessionStorage.getItem("employees-key"));
},
setItem: function (item) {
sessionStorage.setItem("employees-key", JSON.stringify(item));
}
What can I do to get around this?
Just got a heads-up from Telerik
There is an issue logged in their GitHub repo about the same problem.
You can keep track on the progress here:
https://github.com/telerik/kendo-ui-core/issues/326

bootstrap typehead converting to ajax

I have a working sample with hardcoded data. I am trying to convert it to ajax call using bootstrap-typehead. I am not sure what I am doing wrong, but consol is shwoing error. Could some one help ? Thanks!
//Error
LOG: [object Object],[object Object],[object Object],[object Object]
SCRIPT438: Object doesn't support property or method 'toLowerCase'
JSFIDDLE
$('#selectAgent').typeahead({
source: function (query, process) {
return $.post('/eBus/EbusinessAgentServlet', { query: query }, function (data) {
console.log(data)
return process(data);
});
}
,
minLength: 2,
highlighter: formatRecord,
updater: function (item) {
$('#selectAgent').attr('data-agent-id', item.split('#')[1]);
return formatRecord(item);
}
});
It is working now.
var nameIdMap = {};
$('#selectAgent').typeahead({
source: function (query, process) {
return $.ajax({
dataType: "json",
url: '/eBus/EbusinessAgentServlet',
data: 'q=' + query,
type: 'POST',
success: function (json) {
console.log(json)
process(getOptionsFromJson(json));
}
});
},
minLength: 2,
updater: function (item) {
console.log('selected id'+nameIdMap[item]);
return item;
}
});
});
function getOptionsFromJson(json) {
$.each(json, function (i, v) {
nameIdMap[v.fname] = v.agentID;
});
return $.map(json, function (n, i) {
return n.fname;
});
}
function getAjaxRequestData(query) {
return {
json: getJsonData(query),
delay: 1
};
// in the question this would be:
// return 'q='+query;
}
I think that because you're using ajax but javascript is has asyn (default) so you can try to using ajax this way to set async: false . Hpe this help.
$('#selectAgent').typeahead({
source: function (query, process) {
return $.ajax({
url: "/eBus/EbusinessAgentServlet",
data: { query: query },
type: "POST",
async: false,
success: function (data) {
console.log(data)
return process(data);
}
});
},
minLength: 2,
highlighter: formatRecord,
updater: function (item) {
$('#selectAgent').attr('data-agent-id', item.split('#')[1]);
return formatRecord(item);
}
});

Kendo UI reload treeview

I load a complex treeview with kendo ui via ajax because I need to load the tree with one request (works fine):
$(document).ready(function() {
buildTree();
});
function buildTree(){
$.getJSON("admin_get_treedata.php", function (data) {
$("#treeview").kendoTreeView({
select: function(item) { editTreeElement(item,'tree'); },
dataSource: data
});
})
}
If I try to reload the complete tree after changing some data via ajax the new build tree does not work correct and does not update the text.
$.ajax({
type: 'POST',
url: 'ajax/ajax_update_layer.php',
data: {
layerid:id,
...
},
success: function(data){
buildTree();
}
});
What can Ido?
Thanks
Sven
try this on ajax success callback
var data = $("#treeView").data('kendoTreeView');
data.dataSource.read();
I got mine to work.
This is what I did:
Function that creates the tree view:
function CreateNotificationTree(userId)
{
var data = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: "../api/notifications/byuserid/" + userId,
contentType: "application/json"
}
},
schema: {
model: {
children: "notifications"
}
}
});
$("#treeview").kendoTreeView({
dataSource: data,
loadOnDemand: true,
dataUrlField: "LinksTo",
checkboxes: {
checkChildren: true
},
dataTextField: ["notificationType", "NotificationDesc"],
select: treeviewSelect
});
function treeviewSelect(e)
{
var $item = this.dataItem(e.node);
window.open($item.NotificationLink, "_self");
}
}
Modification & data source refresh:
$('#btnDelete').on('click', function()
{
var treeView = $("#treeview").data("kendoTreeView");
var userId = $('#user_id').val();
$('#treeview').find('input:checkbox:checked').each(function()
{
var li = $(this).closest(".k-item")[0];
var notificationId = treeView.dataSource.getByUid(li.getAttribute('data-uid')).ID;
if (notificationId == "undefined")
{
alert('No ID was found for one or more notifications selected. These notifications will not be deleted. Please contact IT about this issue.');
}
else
{
$.ajax(
{
url: '../api/notifications/deleteNotification?userId=' + userId + '&notificationId=' + notificationId,
type: 'DELETE',
success: function()
{
CreateNotificationTree(userId);
alert('Delete successful.');
},
failure: function()
{
alert('Delete failed.');
}
});
treeView.remove($(this).closest('.k-item'));
}
});
});
Hope that helps.

Resources