TypeAhead: error message instead of suggestions data - typeahead

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!

Related

AJAX POST request error - `Uncaught TypeError: Illegal invocation`

If I try to do this, I get this error:
Uncaught TypeError: Illegal invocation
$(document).on('input', '#search-inp', (e) => {
$.ajax({
type: 'POST',
url: '/search/',
dataType: 'json',
data: {
input: $('#search-inp').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]'),
},
success: function(data) {
console.log(data);
}
});
});
And if I try to do this, I get this error:
403: Forbidden
$(document).on('input', '#search-inp', (e) => {
$.ajax({
type: 'POST',
url: '/search/',
dataType: 'json',
processData: false,
contentType: false,
data: {
input: $('#search-inp').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]'),
},
success: function(data) {
console.log(data);
}
});
});
# This is my views.py
def search(request):
return JsonResponse(data={
'test': 'test'
})
What could be the problem?
Your help is greatly appreciated. Thank you
I am so sorry that I bothered everyone.
$(document).on('input', '#search-inp', (e) => {
$.ajax({
type: 'POST',
url: '/search/',
dataType: 'json',
data: {
input: $('#search-inp').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
},
success: function(data) {
console.log(data);
}
});
});
I had done this: csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]')
But should do this: csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()

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);
}
});
}

tag-it :How to diss allow free text

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);
}
});

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