autocomplete jquery-ui with json data is not working small glitch - javascript

I have this code in javascript:
$("#lcountry").autocomplete({
source: function (request, response) {
$.ajax({
url: "https://graph.facebook.com/search?type=adcountry&limit=3",
type: "GET",
data: request,
success: function (data) {
response($.map(data, function (el) {
return {
label: el.name,
value: el.country_code
};
}));
}
});
},
select: function (event, ui) {
// Prevent value from being put in the input:
this.value = ui.item.label;
// Set the next input's value to the "value" of the item.
$(this).next("input").value(ui.item.value);
event.preventDefault();
}
});
unfortunately this doesnt work.When I look at the console here is the result,obviously we can see the countries, I would like to be able to return the name values in jquery autocomplete :
{
"data": [
{
"country_code": "US",
"name": "United States",
"supports_region": "true",
"supports_city": "true"
},
{
"country_code": "AR",
"name": "Argentina",
"supports_region": "false",
"supports_city": "true"
},
{
"country_code": "AU",
"name": "Australia",
"supports_region": "true",
"supports_city": "true"
}
],
"paging": {
"next": "https://graph.facebook.com/search?type=adcountry&limit=5&term=c&offset=5"
}
}

You need to use data.data - data is an object which contains a key data having the list of countries
$("#lcountry").autocomplete({
source: function (request, response) {
$.ajax({
url: "https://graph.facebook.com/search?type=adcountry&limit=3",
type: "GET",
data: request,
success: function (data) {
response($.map(data.data, function (el) {
return {
label: el.name,
value: el.country_code
};
}));
}
});
},
select: function (event, ui) {
// Prevent value from being put in the input:
this.value = ui.item.label;
// Set the next input's value to the "value" of the item.
$(this).next("input").value(ui.item.value);
event.preventDefault();
}
});
Demo: Fiddle

Related

DataTable Range Datetime Filter

I've a datatable which i fill with ajax response. In the response i'm getting a string date data. I can write that data on datatable but i can't filter the data with date range. I've try so much way but i can't solve this. some of my trying i get " fnDraw()" is not function or some error like this. how can I make the range filter ?
JavaScrıpt code :
$(document).ready(function () {
var table = $.ajax({
type: "GET",
url: '/History/GetCallbackHistory',
data: { UserId: document.getElementById("callbackuserid").value },
dataType: 'json',
success: function (obj, textstatus) {
$('#callback_table').DataTable({
"pagingType": "input",
"language":
{
"processing": "<div class='loader'>Loading...</div>",
"paginate": {
"previous": "",
"next": ""
},
},
dom: "<'row'<'container-c'pi<'permuheader'<'refresh-button'>><'tlength'l>>>"
+ "<'row'>"
+ "<'row'<'col-sm-12't>r>",
data: obj,
columns: [
{
"data": "Id"
},
{
"data": "DateCallback"
},
{
"data": "callbackId"
},
{
"data": "Task_name"
},
{
"data": "callbackStatus"
},
{
"data": "Point"
},
{
"data": "TransactionType"
},
{
"data": "DateEnd"
}
]
});
},
error: function (obj, textstatus) {
alert(obj.msg);
}
});
$("#datepicker_from").datepicker({
showOn: "button",
buttonImageOnly: false,
"onSelect": function (date) {
minDateFilter = new Date(date).getTime();
table.fnDraw();
}
}).keyup(function () {
minDateFilter = new Date(this.value).getTime();
table.fnDraw();
});
$("#datepicker_to").datepicker({
showOn: "button",
buttonImageOnly: false,
"onSelect": function (date) {
maxDateFilter = new Date(date).getTime();
table.fnDraw();
}
}).keyup(function () {
maxDateFilter = new Date(this.value).getTime();
table.fnDraw();
});
});
$.fn.dataTableExt.afnFiltering.push(
function (oSettings, aData, iDataIndex) {
if (typeof aData._date == 'undefined') {
aData._date = new Date(aData[1]).getTime();
}
if (minDateFilter && !isNaN(minDateFilter)) {
if (aData._date < minDateFilter) {
return false;
}
}
if (maxDateFilter && !isNaN(maxDateFilter)) {
if (aData._date > maxDateFilter) {
return false;
}
}
return true;
}
);
When you use jQuery's ajax like this:
var table = $.ajax({ ... });
You are assigning the jQuery object to your table variable. You are not assigning the DataTable from the success function to the table variable.
This is why, when you try to use table.fnDraw(), you get that specific error: Your table is not a DataTable. The ajax call is asynchronous - it does not return anything from the success call in the normal flow of your code.
Instead, the simplest alternative that I would recommend is to re-arrange your code to use DataTables' built-in support for ajax.
In this new approach we do not need to use the jQuery ajax function at all - so we completely remove that from the code. Instead, we do this:
var table = $('#callback_table').DataTable({
"ajax": {
"method": "GET",
"url": "/History/GetCallbackHistory",
"data": {
UserId: document.getElementById("callbackuserid").value
},
"dataType": "json",
"dataSrc": ""
},
"pagingType": "input",
"language": {
"processing": "<div class='loader'>Loading...</div>",
"paginate": {
"previous": "",
"next": ""
},
},
"dom": "<'row'<'container-c'pi<'permuheader'<'refresh-button'>><'tlength'l>>>" +
"<'row'>" +
"<'row'<'col-sm-12't>r>",
"columns": [{
"data": "Id"
},
{
"data": "DateCallback"
},
{
"data": "callbackId"
},
{
"data": "Task_name"
},
{
"data": "callbackStatus"
},
{
"data": "Point"
},
{
"data": "TransactionType"
},
{
"data": "DateEnd"
}
]
});
The main point to note is the ajax section:
"ajax": {
"method": "GET",
"url": "/History/GetCallbackHistory",
"data": {
UserId: document.getElementById("callbackuserid").value
},
"dataType": "json",
"dataSrc": ""
},
This is a wrapper around the jQuery ajax function. But it also uses a DataTables extension to jQuery's ajax: the dataSrc option. This option replaces your old data: obj option. It tells DataTables that your JSON response is a plain array.
Once you have done this, then your table variable will contain a valid DataTables object - and you can now use table.fnDraw();. But it would be better to use the modern name for this function: table.draw();.
If you have filtering problems, after that, you can refer to the official date range filtering example DataTables date range filter, to make sure your approach matches the example's approach (but using your preferred datepicker controls).

select2 initial values are being replaced when a new value is selected

Below is my code for a Select2 box. I need values (tags) already assigned to a record to show initially, this is represented by the AAA and BBB values. Then I need to ajax in a list of values to pick from if they want to add new values (tags) to the already existing ones. Everything works except when they select a new value (tag) to add it replaces the existing ones, they disappear. I need them to stay.
<select class="myTags" style="width:100%" multiple="multiple"></select>
<script>
function formatResults(item) {
if (item.loading) return 'Loading...';
return '<div style="font-size:100%;">'+
'<div style="padding:5px;">'+
'<span style="background-color:##e4e4e4; color:##000000; border:1px solid ##aaa; padding:5px;">'+
item.tag+
'</span>'+
'<span style="padding:5px;">'+
' x '+item.popularity+
'</span>'+
'<p style="margin-bottom:0px;">'+
item.description+
'</p>'+
'</div>'+
'</div>';
}
function formatSelection(item) {
return item.tag;
}
jQuery(".myTags").select2({
placeholder: "add a tag, max 20 tags",
maximumSelectionLength: 20,
minimumInputLength: 2,
templateResult: formatResults,
templateSelection: formatSelection,
initSelection: function (element, callback) {
var data = [{ "tag": "AAA", "id": "111" },{ "tag": "BBB", "id": "222" }];
callback(data);
},
escapeMarkup: function (markup) { return markup; }, // let select2's custom formatter work
ajax: {
url: "tags.cfc?method=json_get_valtags",
dataType: 'json',
data: function (params) {
return {
q: params.term
};
},
processResults: function (data) {
return {
results: jQuery.map(data, function (item) {
return {
id: item.UNID,
tag: item.TAG,
description: item.DESCRIPTION,
popularity: item.POPULARITY
}
})
};
}
}
});
</script>
I figured it out. This SO post was very similar to what I needed but I had to tweak it some for my specific scenario.
(1) I had to add the select2 data option...
data: [{ "tag": "AAA", "id": "112233" },{ "tag": "BBB", "id": "11223344" }],
(2) Then I removed the entire initSelection function from the options.
(3) Then I added this at the bottom after the select2 initialization...
jQuery(".myTags").val([112233,11223344]).trigger('change');
So this is the end result...
jQuery(".myTags").select2({
data: [{ "tag": "aaa", "id": "112233" },{ "tag": "bbb", "id": "11223344" }],
placeholder: "add a tag, max 20 tags",
maximumSelectionLength: 20,
minimumInputLength: 2,
templateResult: formatResults,
templateSelection: formatSelection,
escapeMarkup: function (markup) { return markup; }, // let select2's custom formatter work
ajax: {
url: "tags.cfc?method=json_get_valtags",
dataType: 'json',
data: function (params) {
return {
q: params.term
};
},
processResults: function (data) {
return {
results: jQuery.map(data, function (item) {
return {
id: item.UNID,
tag: item.TAG,
description: item.DESCRIPTION,
popularity: item.POPULARITY
}
})
};
}
}
});
jQuery(".cmprotags").val([112233,11223344]).trigger('change');

send json from php to autocomplete and add data attribute in input

[{
"sysid": "39",
"name": "John",
"code": "060400000"
}]
$(document).on("input", ".autocomplete", function(event) {
var name = $(this).prop('id').split('_').pop();
$(".autocomplete").autocomplete({
source: function(request, response) {
$.ajax({
type: 'POST',
url: 'autocomplete.php',
dataType: "json",
data: {
keypressed: request.term,
name: name
},
success: function(data) {
//response(data);
response($.map(data, function(item) {
return {
name: item.name,
code: item.code,
sysid: item.sysid
};
}));
}
});
},
minLength: 2
});
})
This is my sample data
[{
"sysid": "39",
"name": "John",
"code": "060400000"
}]
In my autocomplete if I use response(data); in success and $name[] = ucwords(strtolower($selected_row[$columnename])); in php page all is good but I want to add additional information for my input text like code and sysid.. So I did
$name[] = array('sysid' => $selected_row['sys_id'],'name' => ucwords(strtolower($selected_row[$columnename])),'code' => $selected_row[$columnecode]); in php and in success
response($.map(data, function(item) {
return {
name: item.name,
code: item.code,
sysid: item.sysid
};
}));
What I want to achieve is add data-code and data-idin input after completing autocmplete.
Is this possible?Any Ideas
UPDATE
Used this below but the one changing is the dropdown values what I want is the input to change like
<input data-id="39" data-code="060400000">
response($.map(data, function(item) {
return {
title: item.name,
value: item.name
};
}));
Use the render item function
$(".autocomplete").data("ui-autocomplete")._renderItem = function(ul, item) {
return '<li data-code="'+item.code+'" data-id="'+item.sysid+'">'+item.name+'</li>'
}
for more info visit

loading data in datatable on onchange event

I want to implement function in which data will be loaded into datatable after onChange event. So for that I am trying to implement code as below.
var viewdatatab = $('#dataTablesFeedback').dataTable({
"columns": [
{ "data": "resourceId" },
{ "data": "feedbackRecommendation" },
{ "data": "technicalSkillGaps" },
{ "data": "technicalAvgSkills" },
{ "data": "feedbackType" },
{ "data": "feedbackId" },
{ "data": "isNew" },
]
});
Which is creating my datatable layout and I am calling below function on dropdown change event is :
function loadFeedback(){
viewdatatabJS = $('#dataTablesFeedback').dataTable({
"processing" : true,
"retrieve" : true,
"ajax" : "/nhp/rest/feedback/viewFeedback",
"fnServerParams": function ( aoData ) {
aoData.push( { "name": "userName", "value":employeeId } ,
{ "name": "resourceId", "value":mentorDataJson[$('#dropDownId').val()].resourceId });
},
});
}
Where I am passing some parameter in aoData.push but my URL is not getting called.
I Solved the issue by simply implementing datatable properties. i wrote my code of datatable
var viewdatatab = $('#dataTablesFeedback').dataTable({
"columns": [
{ "data": "resourceId" },
{ "data": "feedbackRecommendation" },
{ "data": "technicalSkillGaps" },
{ "data": "technicalAvgSkills" },
{ "data": "feedbackType" },
{ "data": "feedbackId" },
{ "data": "isNew" },
]
});
in jsp document.ready(function()) and then on my request call of drop down change event i wrote below code on my javascript function.
$.ajax({
url : "",
type: 'GET',
contentType: "application/json",
data: {
'userName': value,
'resourceId' : value,
},
success: function(data) {
var table = $('#dataTablesFeedback').DataTable();
table.clear();
table.rows.add(data.data);
table.draw();
});
this way i first clear my datatable and then redraw it using my json which i got from my ajax call.
Thanks

Select2 AJAX with JSON

I have been trying to populate my input with select2 using the JSON provided.
Here's the JSON:
{
"airports":
[
{
"id": "1",
"code": "AMQ",
"city": "Ambon",
"country": "Indonesia"
},
{
"id": "2",
"code": "BJW",
"city": "Bajawa",
"country": "Indonesia"
}
]
}
And the html code:
<input class="" type='hidden' value="192" data-init-text='Departing City' name='input' id='depart-airport' style="width: 300px"/>
And the js code:
$(document).ready(function() {
$('#depart-airport').select2({
minimumInputLength: 1,
ajax: {
url: "http://localhost:4000/api/airports.json",
dataType: 'json',
results: function (data) {
return { results: data};
}
}
});
});
There's no error in console, but whether I try to input them it's always saying that "searching failed" or there's not even anything. The data from json never showed.
Do you have anything to fix this around? Thanks's before :)
You have a minor error in your jQuery:
$(document).ready(function() {
$('#depart-airport').select2({
minimumInputLength: 1,
ajax: {
url: "http://localhost:4000/api/airports.json",
dataType: 'json',
results: function (data) {
// You had { results: data }, but your actual information is in data.airports
return { results: data.airports };
}
}
});
});

Categories

Resources