put the dynamic data in dropdown list using select2.js - html

I am tried to get the data from my file using ajax in select2.js. I want to get data according the value which I entered in my textbox and append that value in my dropdown using select2. I tried for that but it didn't give the result according my search keyword how to solve these problem.
Here is my input box on HTML:
<input type="text" id="Address1" name="Address1" >
Javascript Code
<script>
$("#Address1").select2({
tags: [],
ajax: {
url: 'ajaxhandler.php',
dataType: 'json',
type: "POST",
// quietMillis: 50,
data: function (term) {
return {
term: term
};
},
results: function (term) {
}
}
});
</script>
ajaxhandler.php
<?php
$CITIES = array("Ahmedabad", "Mumbai", "USA", "Canada", "Pune");
echo json_encode($CITIES); exit;
?>

Data format for Select2.js (version 4) is:
{
"results": [
{
"id": 1,
"text": "Option 1"
},
{
"id": 2,
"text": "Option 2"
}
]
}
See: https://select2.org/data-sources/formats
So you need to processResults received form server like below:
processResults: function (data) {
return {
results: $.map(data.items, function(obj, index) {
return { id: index, text: obj };
})
};
},
Here is a fiddle: http://jsfiddle.net/beaver71/cwb9r23b/

Related

jquery autocompletion json

Jquery UI autocompletion does not work with my JSON file. I want to display the values of the name key. Can you help me?
cluster.json :
[
{
"name": "A128",
"ra": "24.97",
"dec":"12.210"
},
{
"name": "AB 1317",
"ra": "22.55",
"dec": "37.124"
},
{
"name": "UBA 133",
"ra": "35.6",
"dec": "16.44"
},
{
"name": "UGC 69",
"ra": "35.6",
"dec": "16.44"
}
and Jquery in HTML:
$('#name').autocomplete({
source : function(request, response) {
$.ajax({
url :'cluster.json',
dataType : 'json',
data : request,
success: function(data) {
response($.map(data, function(item) {
return item.name;
}));
}
});
}
});
When I enter a character there is this error message in the console:
Erreur d’analyse XML : erreur de syntaxe
Emplacement : file:///C:/Users/xxxx/xxxxx/json/cluster.json?term=A
Numéro de ligne 1, Colonne 3 :
Thank you for your help.
Consider the following:
var myData = [];
$.getJSON("cluster.json", function(data){
myData = $.map(data, function(v, k){
return v.name;
});
});
$('#name').autocomplete({
source: myData
});
If you want to filter the results on your own, you can do that in a number of ways.
This will filter the results based on the input. The final code would look like:
var myData = [];
$.getJSON("cluster.json", function(data){
myData = $.map(data, function(v, k){
return v.name;
});
});
$('#name').autocomplete({
source : function(request, response) {
response($.ui.autocomplete.filter(myData, request.term));
});
Both of these examples, I gather all the data first as I assume it's going to be the static data in the JSON file. You could get the data in the source function if you want.
Full Example
var jData = [{
"name": "A128",
"ra": "24.97",
"dec": "12.210"
},
{
"name": "AB 1317",
"ra": "22.55",
"dec": "37.124"
},
{
"name": "UBA 133",
"ra": "35.6",
"dec": "16.44"
},
{
"name": "UGC 69",
"ra": "35.6",
"dec": "16.44"
}
];
$(function() {
var myData = $.map(jData, function(v, i) {
return v.name;
});
$('#name').autocomplete({
source: myData
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="ui-widget">
<label for="name">Name: </label>
<input id="name">
</div>
Hope that helps.

Get specific value from JSON string

I'm trying to get a simple value out of my json string. It seems to be harder than I thought. How can I reach for example the 'name' of the first ModuleAction object in the following JSON (the first array is called 'data'):
[
{
"ModuleController":{
"id":"3"
},
"ModuleActionModuleController":[
{
"id":"4",
"module_action_id":"1",
"module_controller_id":"3",
"ModuleAction":{
"id":"1",
"name":"Overzicht",
"action":"index"
}
},
{
"id":"5",
"module_action_id":"2",
"module_controller_id":"3",
"ModuleAction":{
"id":"2",
"name":"Detail",
"action":"view"
}
}
]
}
]
Here's my best attempt:
data[0].ModuleActionModuleController[0].id
But I've got the error:
add:93 Uncaught TypeError: Cannot read property '0' of undefined
at Object.success (add:93)
at j (jquery-2.1.0.min.js:2)
at Object.fireWith [as resolveWith] (jquery-2.1.0.min.js:2)
at x (jquery-2.1.0.min.js:4)
at XMLHttpRequest.<anonymous> (jquery-2.1.0.min.js:4)
Any idea what I'm doing wrong? :)
EDIT
Here's the ajax function that returns the data JSON string:
$(function() {
$('#PageModuleId').on('change', function(){
var formData = $('#PageAddForm').serialize();
// POST to server
$.ajax({
type: 'POST',
url: '<?php echo $this->here; ?>',
dataType: 'text',
data: formData,
success: function(data){
console.log(data[0].ModuleActionModuleController[0].ModuleAction.name);
}
});
});
});
How can I reach for example the 'name' of the first ModuleAction
object in the following JSON?
It appears to me that you are just missing the next child element: ModuleActionModuleController.ModuleAction.name
$(document).ready(function() {
var obj = jQuery.parseJSON( '{"ModuleController":{"id":"3"},"ModuleActionModuleController":[{"id":"4","module_action_id":"1","module_controller_id":"3","ModuleAction":{"id":"1","name":"Overzicht","action":"index"}},{"id":"5","module_action_id":"2","module_controller_id":"3","ModuleAction":{"id":"2","name":"Detail","action":"view"}}]}' );
//alert( obj.ModuleActionModuleController[0].ModuleAction.name );
document.body.innerHTML = obj.ModuleActionModuleController[0].ModuleAction.name;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This works for me:
var JSON = {
"data": [
{
"ModuleController":{
"id":"3"
},
"ModuleActionModuleController":[
{
"id":"4",
"module_action_id":"1",
"module_controller_id":"3",
"ModuleAction":{
"id":"1",
"name":"Overzicht",
"action":"index"
}
},
{
"id":"5",
"module_action_id":"2",
"module_controller_id":"3",
"ModuleAction":{
"id":"2",
"name":"Detail",
"action":"view"
}
}
]
}
]
};
alert(JSON.data[0].ModuleActionModuleController[0].ModuleAction.id);

Web API Odata not returning correct metadata

I'm using OData v4 with Web API to communicate with my AngularJS web application.
More specifically I'm trying to display my data using Kendo UI Grid.
My problem is, that my Web API does not return the correct metadata, resulting in Kendos datasource not being able to display the data.
I'm doing paging, and to do that I need the "count" property in my response for Kendo UI Grid datasource to be able work properly.
The response I'm expecting the Web API should look something like this:
http://docs.oasis-open.org/odata/odata-json-format/v4.0/errata02/os/odata-json-format-v4.0-errata02-os-complete.html#_Toc403940644
However, the result I'm seeing in the response is:
{
"#odata.context":"http://localhost:1983/odata/$metadata#TestReports","value":[
{
"Id":1,"Name":"Test Testesen","Purpose":"Kendo UI Grid Test","Type":"Rumraket","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
},{
"Id":2,"Name":"Gunner Testesen","Purpose":"OData Web API Test","Type":"Sutsko","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
},{
"Id":3,"Name":"Bertram Didriksen","Purpose":"Server Paging Test","Type":"Flyver","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
},{
"Id":4,"Name":"Oluf Petersen","Purpose":"Test","Type":"B\u00e5d","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
},{
"Id":5,"Name":"Alfred Butler","Purpose":"Opvartning","Type":"Batmobil","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
}
]
}
My code for retrieving the data is:
$scope.pendingReports = {
dataSource: {
type: "odata",
transport: {
read: {
beforeSend: function (req) {
req.setRequestHeader('Accept', 'application/json;odata=fullmetadata');
},
url: "/odata/TestReports",
dataType: "odata"
},
parameterMap: function (options, type) {
var paramMap = kendo.data.transports.odata.parameterMap(options);
console.log(paramMap);
delete paramMap.$inlinecount; // <-- remove inlinecount parameter
delete paramMap.$format; // <-- remove format parameter
console.log(paramMap);
return paramMap;
}
},
schema: {
data: function (data) {
return data; // <-- The result is just the data, it doesn't need to be unpacked.
},
total: function (data) {
return data.length; // <-- The total items count is the data length, there is no .Count to unpack.
}
},
pageSize: 5,
serverPaging: true,
serverSorting: true
},
sortable: true,
pageable: true,
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
},
columns: [
{
field: "Name",
title: "Navn"
}, {
field: "ReportedDate",
title: "Indberetet den"
}, {
field: "Purpose",
title: "Formål"
}, {
field: "Type",
title: "Type"
}, {
field: "options",
title: "Muligheder"
}
]
};
My WebApiConfig class is corrently like this:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Formatters.InsertRange(0, ODataMediaTypeFormatters.Create());
config.MapODataServiceRoute(
routeName: "odata",
routePrefix: "odata",
model: GetModel()
);
}
public static Microsoft.OData.Edm.IEdmModel GetModel()
{
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<TestReport>("TestReports");
return builder.GetEdmModel();
}
}
Does anyone have any suggestions on how I get the Web API to return the correct metadata?
Apparently Kendo UI Grid is not supporting OData v4.
The fix was to modify the parameterMap of the Kendo datasource, and tell it to use $count instead of $inlinecount.
Besides that I had to tell the schema to read "#odata.count" as the "total" value.
After I edited the before posted code to the ode below, I got the correct data in my response:
$scope.pendingReports = {
dataSource: {
type: "odata",
transport: {
read: {
beforeSend: function (req) {
req.setRequestHeader('Accept', 'application/json;odata=fullmetadata');
},
url: "/odata/TestReports",
dataType: "json"
},
parameterMap: function (options, type) {
var d = kendo.data.transports.odata.parameterMap(options);
delete d.$inlinecount; // <-- remove inlinecount parameter
d.$count = true;
return d;
}
},
schema: {
data: function (data) {
return data.value; // <-- The result is just the data, it doesn't need to be unpacked.
},
total: function (data) {
return data['#odata.count']; // <-- The total items count is the data length, there is no .Count to unpack.
}
},
pageSize: 5,
serverPaging: true,
serverSorting: true
},
sortable: true,
pageable: true,
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
},
columns: [
{
field: "Name",
title: "Navn"
}, {
field: "ReportedDate",
title: "Indberetet den"
}, {
field: "Purpose",
title: "Formål"
}, {
field: "Type",
title: "Type"
}, {
field: "options",
title: "Muligheder"
}
]
};

Sencha touch2: How can i parse my nested json data?

i could not able to parse my nested json data and i tried in many ways but i could not succeed. any help is appreciated.
Here is my json output looks like:
[
{
"task": {
"locator": "FGWESD",
"subtask": [
{
"work": {
"number": "1145",
"id": "0",
"status": true,
"gate": "N\/A",
},
"sequenceNumber": "0",
"id": "0"
},
{
"work": {
"number": "1145",
"id": "0",
"status": true,
"gate": "N\/A",
},
"sequenceNumber": "0",
"id": "0"
}
],
"connectTime": "0",
"id": "0"
}
}
]
Here is my model:
Ext.define('MyApp.model.MyModel',{
extend:'Ext.data.Model',
xtype:'myModel',
config:{
fields:[
{name:'number',mapping:'work.number'},
{name:'id',mapping:'work.id'},
{name:'locator',mapping:'task.locator'},
{name:'gate',mapping:'work.gate'}
]
}
});
Here is the store:
Ext.define('MyApp.store.StoreList', {
extend:'Ext.data.Store',
config:{
model:'MyApp.model.MyModel',
storeId: 'id_Store',
// added the url dynamically inside the controller
proxy:{
type:'ajax',
reader:
{
type:"json",
rootProperty: 'subtask'
},
method: 'POST',
actionMethods: {
create : 'POST',
read : 'POST', // by default GET
update : 'POST',
destroy: 'POST'
},
headers :{
"Content-Type" :'application/xml',
'Accept':'application/json'
}
}
}
});
Here is my controller code :
Ext.define('MyApp.controller.LoginController', {
extend: 'Ext.app.Controller',
requires: ['Ext.data.proxy.Rest'],
config: {
// My code is too long to add here so am adding store loading when user taps login button
},
getDetails: function(){
var segmentStore = Ext.create('MyApp.store.StoreList');
var url = 'http://localhost:8080/apps';
segmentStore.getProxy().setUrl(url.trim());
segmentStore.load({
scope:this,
callback: function(records, operation, success){
if(success){
console.log('records: ',records);
console.log('records: '+records.length); // prints here 1
console.log('locator: '+records[0].getData().locator);
// prints FGWESD
console.log('locator: '+records[0].getData().number);
//prints undefined
//
}
}
}
)
},
});
Can any one please help me out. how can i get Values of number, gate, id and status?
What are the necessary changes have to be made in model, store and controller ?
Please help me out in resolving ? Thanks.
As I wrote in a comment, I don't think you can achieve that without manually parsing the data and loading it to the store. So the getDetails function should look like this:
getDetails: function(){
var segmentStore = Ext.create('MyApp.store.StoreList');
Ext.Ajax.request({
url: 'http://localhost:8080/apps',
success: function(response){
var responseObj = Ext.decode(response.responseText);
var task = responseObj[0].task;
var locator = task.locator;
var subtasks = [];
Ext.each(task.subtask, function(subtask) {
subtasks.push({
number: subtask.work.number,
id: subtask.work.id,
gate: subtask.work.gate,
locator: locator
});
});
segmentStore.setData(subtasks);
}
});
}
Also, when using this method you should remove the mapping from your model, and you can get rid of the proxy definition of the store. Also, I'm not sure why you want to create the store in the "getDetails" and not define it in the 'stores' config of the controller, but maybe you have your reasons..
I didn't run the code, so there maybe errors, but I hope you get the idea.
I think the root property of your store should be:
rootProperty: 'task.subtask'

Jqgrid doesn't reload when using pager

i want my jqgrid programmatically move next page with reloaded data. for example: every 5 seconds change page and get refreshed data.
---> datatype: 'json' <---
is in loop() function. brings reloaded page, but it does not pass the next page. stuck on the first page. if i delete it goes the next page, but the page doesn't refresh.
i read and tried, tried, tried everything but no luck as of yet. Please help..
<script>
function fill() {
jQuery("#jqGrid").jqGrid({
url: '#Url.Content("~/Handler/GetAjaxGridData")',
datatype: 'json',
height: 'auto',
altRows: true,
loadonce:true,
pager: '#pager',
rowNum: 3,
colNames: ['birim_adi', 'durum'],
colModel: [
{ name: 'cell.birim_adi', index: 'birim_adi' },
{ name: 'cell.durum', index: 'durum' }
],
jsonReader: {
repeatitems: false,
root: function (obj) { return obj.rows; },
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.rows.length; }
},
loadComplete: function (data) {
var total_pages = $("#sp_1_pager").text(); // total pages
$('#hdn_total_pages').val(total_pages);
},
ajaxGridOptions: { cache: false }
});
}
function loop() {
var i = 1;
setInterval(function () {
var total_pages = $('#hdn_total_pages').val();
$("#jqGrid").setGridParam({
datatype: 'json', // <--When I delete it goes to another page, but the page does not refresh.
page: i,
}).trigger('reloadGrid');
i++;
if (i > total_pages) { i = 1; }
}, 5000);
}
</script>
<script>
$(function () {
fill();
loop();
});
</script>
<table id="jqGrid"></table>
<div id="pager"></div>
<input type="hidden" id="hdn_total_pages" value="1" />
and then my json like this:
{
"total": 1,
"page": 1,
"records": 6,
"rows": [
{
"id": 1,
"cell": {
"birim_adi": "a",
"durum": "test"
}
},
{
"id": 2,
"cell": {
"birim_adi": "b",
"durum": "test1"
}
},
{
"id": 3,
"cell": {
"birim_adi": "c",
"durum": "test3"
}
},
{
"id": 4,
"cell": {
"birim_adi": "d",
"durum": "test4"
}
}
]
}
The jsonReader is returning a hard-coded value of '1' for page. It looks like your data conforms to the structure jqGrid will work with automatically. You might just try deleting the jsonReader section entirely and give it a shot.
If that's not working (or your data has different names than jqGrid is expecting) you will need to look at fixing jsonReader to return proper values.
Take a look at this blog entry about customizing the jsonReader to work with different data formats. It might help you resolve the page getting stuck. (Full disclosure: I'm the author.)