AJAX results issue - Data.Results is Undefined - ajax

I am trying to setup Select2 to use Ajax and am rather stuck. I have debugged in IE and confirmed that my AJAX is returning results, so that doesn't appear to be the issue. The input box loads, but when I type "mi" in for "milk" it just says "searching..." and never finds anything!
Here is my Jquery:
$(document).ready(function () {
$('#e1').select2({
placeholder: "Select an ingredient...",
minimumInputLength: 2,
ajax: {
url: "../api/IngredientChoices",
dataType: "jsonp",
quietMillis: 500,
data: function (term, page) {
return {
q: term,
page_limit: 10,
page: page
};
},
results: function (data, page) {
var more = (page * 10) < data.total;
return {
results: data.MainName, more:more
}
}
}
});
});
JSON:
[{"SubItemID":1,"MainItemID":1,"SubName":"2%","MainName":"Milk"},{"SubItemID":2,"MainItemID":1,"SubName":"Skim/Fat Free","MainName":"Milk"},{"SubItemID":3,"MainItemID":2,"SubName":"Chedder","MainName":"Cheese"}]
HTML:
<td><input type="hidden" id="e1" /></td>
If I change the dataType to be just json I get a different kind of error when I type "mi" into the box.
Here is the final code for the working version:
$('#e1').select2({
placeholder: "Select an ingredient...",
minimumInputLength: 2,
ajax: {
url: "../api/IngredientChoices",
dataType: "json",
quietMillis: 500,
data: function (term, page) {
return {
q: term,
page_limit: 10,
page: page
};
},
results: function (data, page) {
var more = (page * 10) < data.length;
console.log(more);
console.log(data);
return { results: data, more: more };
},
formatResult: function (post) {
markup = '<strong>' + post.text + '</strong>';
}
}
});

The error you are encountering appears to be because of the format of the results you are getting. Select2 is expected results to be a collection of objects with id: and text: attributes.
[{ id: 1, text: 'String' }, { id: 2, text: 'Other String.'}]

Related

Select2 - Change name="param" to other name for post request

I have the following search box for getting data from backend:
<select class="form-control kt-select2" id="megaagent_rainmaker_select" name="param" multiple="multiple" style="width: 100%"></select>
This is my select2 javascript code:
var rainmakerSelect = function () {
// Private functions
var demos = function () {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
// multi select
$('#megaagent_rainmaker_select').select2({
language: "es",
placeholder: "Escriba y seleccione",
allowClear: true,
maximumSelectionLength: 1,
ajax: {
url: '/admin/megaagent/getrainmaker',
type: "get",
dataType: 'json',
delay: 150,
data: function (params) {
return {
_token: CSRF_TOKEN,
search: params.term // search term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: true
}
});
}
return {
init: function () {
demos();
}
};
}();
jQuery(document).ready(function () {
rainmakerSelect.init();
});
I get results returned and I can select one without problem.
After I select a value, I send update request to backend, this is my payload:
{
"_token": "bPl0hZJQxw5wAxNCqVOOKqrXXwkD5AZZOFPumrpC",
"mc_id": "11",
"megaagent_id": "16",
"megaagent_name": "David Cortada",
"megaagent_business_name": "bsame cambio",
"megaagent_uma_id": "umaid",
"megaagent_api_key": "apikey",
"param": "963",
"megaagent_phone_number": "phone",
"megaagent_email": "email",
"megaagent_address": "address",
"megaagent_facebook": "fb",
"megaagent_instagram": "inst",
"megaagent_twitter": "twi",
"megaagent_linkedin": "link",
"megaagent_image": "image",
"megaagent_status": "Activo"
}
What I want to achieve is to change param name to other on post request (example: "megaagent_rainmaker_id" = "963",.
I changed it in <select name="param"> but that breaks the search, no results are returned when I type in search box.
Does anyone knows the solution for this?
Regards

highcharts line graph with ajax

I would like to implement a simple line graph with ajax in which only two points
x will be the hours and y will be the count of calls.
CODE :
<script>
function getData() {
$.ajax({
type:'POST',
url: "http://localhost/demo_chart/test.php",
dataType: 'JSON',
success: function(response_data) {
new_data = $.map(response_data, function(i){
return {x: i['date'],y: i['count']};
});
$('#container').highcharts({
chart: {
renderTo: 'container',
type: 'line'
},
title: {
text: 'Count vs. Time'
},
xAxis: {
title: {
text: 'Time'
},
type: 'Time',
},
yAxis: {
title: {
text: 'Count'
}
},
series: [{
name: 'Test',
data: new_data
}]
});
}
})
}
$(document).ready(function () {
getData();
})
</script>
Output of http://localhost/demo_chart/test.php is same as below :
{"date":["13:00:00","13:00:01","13:00:02","13:00:03","13:00:04"],"count":["1","2","3","4","2"]}
But still graph is not generating. So i would like to know what is the problem here.
Anyone like to share some hint which can resolve this problem ?
Expected output is :
X- axis : show all date
Y-axis : show count
You need to correct your mapping function, for example:
var response = {
"date": ["13:00:00", "13:00:01", "13:00:02", "13:00:03", "13:00:04"],
"count": ["1", "2", "3", "4", "2"]
};
new_data = $.map(response.date, function(el, index) {
return {
name: el,
y: parseInt(response['count'][index])
};
});
Additionally, with that data structure, I recommend you to use category axis type.
xAxis: {
...,
type: 'category'
}
Live demo: http://jsfiddle.net/BlackLabel/ptx6fy2q/
API Reference: https://api.highcharts.com/highcharts/xAxis.type

JQuery-ui autocomplete feature with id and value in response, but how to display value in autocomplete text box and id in hiddenbox text

I am getting Spring JPA response in below format
[
[12, "companyReferenceNumber1"],
[13, "companyReferenceNumber2"],
[14, "companyReferenceNumber3"],
[15, "companyReferenceNumber4"],
[16, "companyReferenceNumber5"],
[17, "companyReferenceNumber6"],
[18, "companyReferenceNumber7"],
[19, "companyReferenceNumber8"],
[20, "companyReferenceNumber9"],
[21, "companyReferenceNumber10"]
]
and reaching towards ajax -> success -> data parameter
now I wanted to show only value in autocomplete text box and key in hidden. Tried all the ways to do it, but I may be missing some small thing somewhere. A little look and help on my code will be truly helpful. Stuck since 4 days now.
//Adding JQuery code
$("#employeeId").autocomplete({
source: function(request, response) {
$.ajax({
url: "/searchEmployeeId",
data: {
term: request.term
},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.name,
value: item.name
};
}));
}
});
},
select: function(event, ui) { //Error here : ReferenceError: item is not defined
$("#employeeId").val(ui.item[1]);
$("#empId").val(ui.item[0]);
alert(ui.item + "d");
return false;
},
change: function(event, ui) {
$("#employeeId").val(ui.item ? ui.item.value : 0);
},
minLength: 2
});
Somehow it started working. Below is the solution. Will keep updating if I have any updates.
$("#employeeId").autocomplete({
source: function(request, response) {
$.ajax({
url: "/searchEmployeeId",
data: {
term: request.term
},
success: function(data) {
response($.map(data, function(item) {
return {
label: item[1],
value: item[0]
};
}));
}
});
},
select: function(event, ui) {
$("#employeeId").val(ui.item.label);
$("#empId").val(ui.item.value);
return false;
},
focus: function(event, ui) {
$("#employeeId").val(ui.item.label);
return false;
},
change: function(event, ui) {
$("#employeeId").val(ui.item ? ui.item.label : 0);
},
minLength: 2
});
$("#employeeId").autocomplete("option", "appendTo", ".eventInsForm");

Kendo MVVM Grid - Transport.create not being executed

I have the following Kendo MVVM grid:
<div id="permissionTypeGrid" data-role="grid"
data-sortable="true"
data-scrollable="true"
data-editable="true"
data-toolbar="['create', 'save', 'cancel']"
data-bind="source: permissionTypes"
data-auto-bind="true"
data-columns="[
{ 'field': 'PermissionType', 'width': 60 },
{ 'field': 'Description', 'width': 300 },
{ 'field': 'DisplayOrder', 'width': 60 },
{ 'command': [{name: 'destroy', text: 'Delete'}], 'width': 40 }
]">
</div>
And the following view model:
self.permissionTypeGrid = kendo.observable({
isVisible: true,
permissionTypes: new kendo.data.DataSource({
schema: {
parse: function (results) {
var permissionTypes = [];
for (var i = 0; i < results.Data.Data.length; i++) {
var permissionType = {
PermissionType: results.Data.Data[i].SystemPermissionTypeCode,
Description: results.Data.Data[i].SystemPermissionTypeDescription,
DisplayOrder: results.Data.Data[i].DisplayOrder
};
permissionTypes.push(permissionType);
}
return permissionTypes;
}
},
transport: {
read: {
url: "/api/ServiceApi?method=Ref/SystemPermissionTypes",
},
create: {
url: "/api/ServiceApi?method=Ref/SystemPermissionTypes"
},
update: {
url: "/api/ServiceApi?method=Ref/SystemPermissionTypes"
},
destroy: {
url: "/api/ServiceApi?method=Ref/SystemPermissionTypes"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
}
})
});
kendo.bind($("#permissionTypeGrid"), self.permissionTypeGrid);
Transport.read works fine, but the url for transport.create is never executed, nor is the parameterMap function. If I add a new record to the grid and then click "Save Changes", shouldn't the parameterMap function always be called? Also, an http request for the read is made as expected, but none gets generated for a create.
You schema needs and ID.
If you add the line model: { id: "DisplayOrder" }, after schema your create will begin firing when you click save changes.
Of course this is not likely to be the field that you will want to use for an ID but it should get you working.
schema: {
model: { id: "DisplayOrder" },
parse: function (results) {
...
}

Is it possible for pagination last button reload in jquery datatable?

Is it possible for pagination last button reload in jquery datatable?
I have used jquery datable ,Now my record more than one lack's data.
So I have page initialize 1000 record load and then last pagination button click reload data 1000.
can give me any other idea...?
For your reference:
$("#tblExmaple").hide();
jQuery(document).ready(function ($) {
getRecords();
function getRecords() {
jQuery.support.cors = true;
$.ajax({
cache: false,
type: "GET",
url: "http://localhost:1111/TestSample/api/getRecords",
datatype: "json",
data: { Arg1: "Values1",Arg2: "Values2",Arg2: "Values3" },
statusCode: {
200: function (data) {
$.each(data, function (index, obj) {
var colRes1 = obj.Res1;
var colRes2 = obj.Res2;
var dataAdd = [colRes1, colRes2];
getData.push(dataAdd);
});
// Server Side Code
setTimeout(function () {
$('#tblExmaple').dataTable({
"sPaginationType": "full_numbers",
"sScrollXInner": "50%",
"sScrollyInner": "110%",
"aaData": getData,
"iDisplayLength": 8,
"sInfoEmpty": false,
"bLengthChange": false,
"aoColumns": [
{ "sTitle": "Column1" },
{ "sTitle": "Column2" }
];
})
}, 500);
setTimeout(function () {
$("#tblExmaple").show();
}, 500);
},
408: function (data) {
var response_Text = JSON.stringify(data, undefined, 50);
if (data.response_Text == undefined) {
window.location = "/Home/Index";
}
else {
timeoutClear();
}
}
}
});
}

Resources