tag-it :How to diss allow free text - tag-it

http://aehlke.github.io/tag-it/
What should i do to avoid free text on tag-it?
I mean user should be able to tag only those strings suggested by auto compelte
$("#selector").tagit({
// Options
fieldName: "projects",
autocomplete: {
minLength: 2,
source: function (request, response) {
$.ajax({
url: '/xxx/xxxx',
type: 'POST',
data: {
searchKey: request.term
},
success: function (data) {
response($.map(data, function (item) {
return { label: item.Name };
}));
}
});
}
},
showAutocompleteOnFocus: false,
removeConfirmation: false,
caseSensitive: false
});

I suggest to somehow combine autocomplete with beforeTagAdded which discards tag from being added by returning false:
$("#selector").tagit({
//...
beforeTagAdded: function(event, ui) {
return isSuggested(ui.tagLabel);
}
});

Related

chart js not dispalying data array that comes from an axios request

I have an API end point that returns an array of 24 values that I want to use in my chartjs within a vue component.
when the page loads I get no errors but the bars on the charts just don't show and I don't know why.
EDIT: I noticed that the async function returns a promise instead of the actual data:
async filterData() {
await this.$axios.get('/api/data_app/job_count_by_hour/')
.then(response => {
return this.chart_data = response.data;
})
}
here is the data return code, I have a function that populates the chart_data array :
data(){
return {
form:{
day: 'select day',
workspace:'',
machine_family: [],
duration: []
},
res: [],
total:[],
chart_data: [],
url: '/api/jobs/job_count_by_hour/',
days: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "sunday"],
barChart2: {
labels: ["6h", "7h", "8h", "9h","10h","11h", "12h", "13h", "14h", "15h", "16h", "17h", "18h", "19h", "20h", "21h","22h", "23h", "00h"],
datasets: [{
label: ["popularity"],
backgroundColor:"#f93232" ,
data: this.chart_data
},],
},
}
},
methods: {
async filterData() {
let _url = `${this.url}`
await this.$axios.get(_url)
.then(response => {
this.chart_data = response.data;
})
return this.chart_data
},
},
mounted() {
this.filterData()
}
}
this is the chart component:
<script>
import { Line } from 'vue-chartjs'
export default {
extends: Line,
props: {
chartdata: {
type: Object,
default: null
},
options: {
type: Object,
default: null
}
},
mounted () {
this.renderChart(this.chartdata, this.options)
}
}
in the parent component It looks like this:
en <BarChart :labels="barChart2.labels"
:datasets="barChart2.datasets"
:height="100"
>
</BarChart>ter code here
Turns out that when you try to update nested data, the component doesn't re-render.
This is how I solved it, I put the entire object in an update function and call that function when i get my data from the back end, I hope this helps!:
methods: {
onInput(value) {
this.filterData()
},
updateChart(data) {
this.datasets = [{
label: ["popularity"],
backgroundColor:"#f93232",
data: data
}]
},
async loadData() {
await this.$axios.get(this.url)
.then(response => {
this.updateChart(response.data)
})
},
},
mounted() {
this.loadData()
},

TypeAhead: error message instead of suggestions data

I am using typeahead library, it's fetching the data successfully. But not loading the data into the suggestions list, instead its showing the unable to find any company that match current query every time.
Here is my code:
$('#js-typeahead').typeahead({
highlight: true,
minLength: 1
}, {
displayKey: ['title'],
source: function(keywords, result) {
ajaxRequest({
url: '{{ route("admin.companies.auto-complete") }}',
dateType: 'json',
data: {
keywords: keywords,
_token: '{{ csrf_token() }}'
},
success: function(response) {
result($.map(response, function(data) {
return {
'title': data.title,
'token': data.token,
};
}));
}
});
},
templates: {
empty: [
'<div class="empty-message">',
'unable to find any company that match current query',
'</div>'
].join('\n'),
suggestion: function(data) {
return '' + data.title + '';
}
}
});
Here is the fetched data
Please tell me what am I doing wrong here.
[SOLVED]: Here is my final code...
$('.js-typeahead').typeahead({
hint: false,
highlight: true,
minLength: 1
}, {
displayKey: 'title',
source: (new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('title'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '{{ route("admin.{$parent['route']}.auto-complete") }}',
prepare: function (keywords, settings) {
return $.extend({}, settings, {
type: "POST",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify({
keywords: keywords,
_token: '{{ csrf_token() }}'
})
});
}
}
})),
templates: {
empty: '<div class="empty">No result found</div>',
suggestion: function (data) {
return '<div>' + data.title + '</div>';
}
},
}).on('typeahead:asyncrequest', function(event) {
$('.js-typeahead').before('<i class="fas fa-spinner fa-spin loading"></i>');
}).on('typeahead:asyncreceive', function(event) {
$('.js-typeahead').prev('.loading').remove();
}).on('typeahead:selected', function(event, selection) {
// window.location.href = selection.token;
});
I hope this may come in handy for someone...
You're code is practically correct. And the best thing is that you can also get the result without using bloodhound.
from the initial code you state, you are calling it synchronously. thats why it does not yield any result.from typeahead docs. here is the highlight
Expected to be a function with the signature (query, syncResults, asyncResults). syncResults should be called with suggestions computed synchronously and asyncResults should be called with suggestions computed asynchronously (e.g. suggestions that come for an AJAX request)
so your initial code part
source: function(keywords, result) {
ajaxRequest({
url: '{{ route("admin.companies.auto-complete") }}',
dateType: 'json',
data: {
keywords: keywords,
_token: '{{ csrf_token() }}'
},
success: function(response) {
result($.map(response, function(data) {
return {
'title': data.title,
'token': data.token,
};
}));
}
});
},
are running synchronously, and because you are fetching data from ajax, you should make it asynchronously like this (i added asyncresult)
source: function(keywords, result, asyncresult) {
ajaxRequest({
url: '{{ route("admin.companies.auto-complete") }}',
dateType: 'json',
data: {
keywords: keywords,
_token: '{{ csrf_token() }}'
},
success: function(response) {
asyncresult($.map(response, function(data) {
return {
'title': data.title,
'token': data.token,
};
}));
}
});
},
hope it helps!

How to pass List<int> to kendo grid read()

I just want to pass list of integer values to read() method.
used "parameterMap" to map parameter. also tried to set data object.
transport: {
read: {
url:
"#Url.HttpRouteUrl("ActionApi", new {controller = "Regions",action = "GetByCountries" })",
//dataType: "json",
contentType: "application/json; charset=utf-8"
},
parameterMap: function (options, operation) {
debugger;
if (operation === "read") {
return { countries: selectedCountries};
}
}
},
my Controller like bellow
[System.Web.Http.ActionName("GetByCountries")]
[System.Web.Http.HttpGet]
public List<Region> GetByCountries(List<int> countries)
{
return new RegionMgt().GetByCountries(countries).ToList());
}
gives null value for countries parameter.
This Work for me :)
transport: {
read: function(options) {
$.ajax({
type: "POST",
url: "#Url.HttpRouteUrl("ActionApi", new { controller = "Regions", action = "GetByCountries" })",
data: JSON.stringify(selectedCountries),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
options.success(result);
}
});
}
},
Hope anyone help...!

Implementing Batch Update in Kendo UI GRID not work

While trying to perform batch update, I am not able to post values to MVC WEB API controller neither I am getting Record IDs in mu PUT controller.
I have already visited some of the links egarding same problem but got no solution.
$(document).ready(function () {
debugger;
var webapiUrl = (My webapi);
dataSource = new kendo.data.DataSource({
type: "json",
transport: {
read: {
url: webapiUrl + api/GetProductsByShipID/1",
contentType: "application/json",
},
update: {
url: webapiUrl + api/OpportunityProducts/1",
contentType: "application/json",
type: "PUT"
},
destroy: {
url: webapiUrl + /api/OpportunityProducts/",
contentType: "application/json",
type: "DELETE"
},
create: {
url: webapiUrl + /api/OpportunityProducts/",
contentType: "application/json",
type: "POST"
},
parameterMap: function (options, operation) {
if (operation !== "read") {
return options;
}
}
},
batch: true,
pageSize: 10,
schema: {
model: {
id: "ID",
fields: {
ID: { editable: false, nullable: true },
ProductDesc: { type: "string" },
Quantity: {type: "number"},
UnitPrice: { type: "number"}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
navigatable: true,
pageable: true,
toolbar: ["create", "save", "cancel"],
columns: [
"ProductName",
{ field: "ProductDesc", title: "Product Desc"},
{ field: "Quantity", title: "Quantity" },
{ field: "UnitPrice", width: 120 },
{ command: "destroy", title: " ", width:150 }],
editable: true
});
});
</script>
Well after some workaround, late night I was able to modify parameterMap section of my kendo grid which lead me to expected output.
This is how I updated my parameterMap section...
Previous
parameterMap: function (options, operation) {
if (operation !== "read") {
return options;
}
}
Updated
parameterMap: function (options, operation) {
debugger;
if (operation !== "read" && options.models) {
var webapiUrl = (my webapi);
var i = 0;
for (i = 0; i < options.models.length; i++) {
$.ajax({
cache: false,
async: true,
type: "PUT",
url: webapiUrl + "/api/OpportunityProducts/" + options.models[i].Id,
data: {
ID: options.models[i].ID,
ProductDesc: options.models[i].ProductDesc,
Quantity: options.models[i].Quantity
},
success: function (data) {
},
error: function (jqXHR, exception) {
alert(exception);
}
});
}

how to access the form data done on a post request in the views using ajax jquery

I'm trying to figure out the best way to send post data to a Django View function.
What I have currently in my jquery code is something like this:
in the jquery:
function ajax_request(type) {
var a="{{parameter}}";
alert(type);
var frm = $('#form1');
form_data=frm.serialize();
alert(form_data);
$.ajax({
type : type,
data: form_data,
url : geturl(a),
dataType : 'json',
)}
i have written i single function called ajax_request. all i need is just access the data i have retrieved in the jquery in my views. how could i get it in my views.
function event_page_load() {
alert("hi");
ajax_request('GET')
}
function click_submit_button() {
ajax_request('POST')
}
function ajax_request(type) {
var a="{{parameter}}";
alert(type);
var frm = $('#form1');
form_data=frm.serialize();
alert(form_data);
$.ajax({
type : type,
data: form_data,
url : geturl(a),
dataType : 'json',
error : function(result) {
alert("error");
// alert("Error occured!!");
},
success : function(result,data)
{
alert("success");
// alert("data");
// $('#container').html(data);
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
marginRight: 220,
marginBottom: 75,
marginLeft:100,
marginTop:80
},
title: {
marginTop:90,
text: 'Power Consumption Vs Generator Consumption'
},
xAxis: {
categories: result[0]
},
yAxis: {
title: {
text: 'Units Of Time'
}
},
series: [{
name: 'Truepower Consumed',
data: result[1]},
{
name: 'Generator Consumed',
data:result[2]}],
});
}
})
}
You can use $.post
$.post({
geturl(a),
{ data: form_data, dataType : 'json' },
// response handler
});
Example :
$.post()
$("#post").click(function(){
$("#result").html(ajax_load);
$.post(
loadUrl,
{language: "php", version: 5},
function(responseText){
$("#result").html(responseText);
},
"html"
);
});
A helpful tutorial is available at http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/
Complete list of Django + AJAX examples are available at https://github.com/sivaa/django-jquery-ajax-exmaples