I am receiving a large JSON object having large volume of data in ajax success method
but when i am iterating over the JSON list and want add individual class to each element things are not working.
The code snippet i am pasting here is inside ajax success method
$.each(data, function(index,jsonObject){
console.log(jsonObject.spanId+":"+jsonObject.status)
if(jsonObject.status != null && jsonObject.status != undefined){
if(jsonObject.status == "Available"){
$('#'+jsonObject.spanId).addClass("availableTime");
}else{
$('#'+jsonObject.spanId).addClass("vacantTime");
}
}
});
I have tried lot but not able to accomplish, please help me.
I am adding chunk of my json object
[
{
"spanId": null,
"status": null
},
{
"spanId": null,
"status": null
},
{
"spanId": "25_31_15:00",
"status": "Available"
},
{
"spanId": "25_31_15:30",
"status": "Available"
},
{
"spanId": "25_31_16:00",
"status": "Available"
},
{
"spanId": "25_31_16:30",
"status": "Available"
},
{
"spanId": "25_31_17:00",
"status": "Available"
}
]
You span ids are not advised and it may be what is not working.
Plus : for selectors is a reserved word for pseudo classes.
Source
Contrary to what you might expect, the use of colons in ids is okay, though only HTML5 started to accept ids starting with a digit. For better interoperability, it's recommended to start ids with a letter and not use colons in the first place.
That said, if you must use colons in your identifiers, you must escape them when you use them as part of a selector:
$('25_31_17\\:00') // this works fine
Alternatively, if you're going to find elements by their identifier, you might also want to consider:
$(document.getElementById(jsonObject.spanId)) // this will work too
H i, just missing a couple of things and data is in the wrong place ( by the looks )
try running this :
$.each(data, function(index){
console.log(data[index].spanId+":"+data[index].status)
});
notice that you need to tell the loop which array item to reference :
data[index]
and that the 'each' is looping over the array:
$.each(data, function(index){ ...
EDIT with data ref:
var data = [
{
"spanId": null,
"status": null
},
{
"spanId": null,
"status": null
},
{
"spanId": "25_31_15:00",
"status": "Available"
},
{
"spanId": "25_31_15:30",
"status": "Available"
},
{
"spanId": "25_31_16:00",
"status": "Available"
},
{
"spanId": "25_31_16:30",
"status": "Available"
},
{
"spanId": "25_31_17:00",
"status": "Available"
}
]
Related
sample data for title
actiontype test
booleanTest
test-demo
test_demo
Test new account object
sync accounts data test
default Mapping for title
"title": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
tried with this query search
{
"query": {
"bool": {
"must": [
{
"match": {
"title": "test"
}
}
]
}
},
}
here my expectation
with specific word(e.g. : test ) it should return following titles
expect
actiontype test
booleanTest
test-demo
test_demo
Test new account object
sync accounts data test
But
got
actiontype test
test-demo
test_demo
Test new account object
sync accounts data test
With exact match (e.g. : sync accounts data test ) it should return only this(sync accounts data test) but got all records those contains this words (sync,account,data,test).
What should I do to make this happen ? Thanks.
I am not sure which ES version you're using but the following should give you an idea.
Using your mapping you can get all title text with test, including booleanTest using query string query type. Eg.
GET {index-name}/{mapping}/_search
{
"query": {
"query_string": {
"default_field": "title",
"query": "*test*"
}
}
}
However, for this to work, make sure you give your title field an analyzer with a lowercase analyzer filter (see below settings example). Your current mapping will not work since it's just pure text as is... test /= TEST by default.
There are other ways, if you're interested to know the workings of ES... Eg. You can also match booleanTest in your match query by writing a custom nGram filter to your index settings. Something like,
{
"index": {
"settings": {
"index": {
"analysis": {
"filter": {
"nGram": {
"type": "nGram",
"min_gram": "2",
"max_gram": "20"
}
},
"ngram_analyzer": {
"filter": [
"lowercase",
"nGram"
],
"type": "custom",
"tokenizer": "standard"
}
}
}
}
}
}
NB: ngram_analyzer is just a name. You can call it whatever.
min_gram & max_gram: Pick numbers that work for you.
Learn more about n-gram filter, the goods and bad here: N-GRAM
Then you can add the analyzer to your field mapping like,
{
"title": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256,
"analyzer": "ngram_analyzer"
}
}
}
}
Lastly for exact matches, these work on type keyword. So based on your mapping, you already have the keyword field so you can use term query to get the exact match by searching on the title.keyword field;
GET {index-name}/{mapping}/_search
{
"query": {
"term": {
"title.keyword": {
"value": "sync accounts data test"
}
}
}
}
Also, you will want to read/ learn more about these solutions and decide on the best solution based on your indexing setup and needs. Also, there may be more ways to achieve what you need, this should be a good start.
I'm using metronic v5.0.7.1 i have a datatable which is contains nested array so i just want to search in this array.
I'm able to bind my case status like that;
{
field: 'case.case_status',
title: "Status",
}
there is my search field;
var query = datatable.getDataSourceQuery();
$('#m_form_durum').on('change', function () {
datatable.search($(this).val(), 'case.case_status');
}).val(typeof query.case.case_status !== 'undefined' ? query.case.case_status : '');
After that im getting this error "Cannot read property 'case_status' of undefined". How can I specify the nested field in this case?
By the way if I replace my field to 'count' which is in my array instead of 'case.case_status' its work very well. Just nested fields give this error.
Also this is my sample data:
[
{
"id": 93,
"case": {
"id": 99,
"case_status": 1,
},
"user": "1",
"count": "2",
"created_at": "2018-02-08T09:00:00.884590+03:00",
"modified_at": "2018-02-08T09:00:00.884612+03:00",
"is_deleted": false,
}
]
I have an json object coming from a $.post in jquery.
In order to loop through and store the data clientside I would like to add it to an array. For each search results that comes back I would like to "append" the array so it grows.
This is my json:
{
"companies": [
{
"companyid": "115",
"saved": false,
"orgnumber": "010101010",
"companyname": "TestCompany",
"header": "header info"
},
{
"companyid": "116",
"saved": false,
"orgnumber": "010101010",
"companyname": "TestCompany",
"header": "header info"
} ]
}
This is what I have come up with so far were data is the json
comming back fron the post ajax request. Obj is just an object holding the array
which I declared further up in my code. obj.companies = new Array();
obj.companies.push(data['companies']);
The next part I need to loop out the array. Trying to do it like this.
$.each(obj.companies, function(i, item) {
// Does not alert correctly.
alert(item.header);
});
So I need to push the full json object into the array. But I cannot alert the item.header within the loop, how can I accomplish this?
EDIT:
Thanks everyone. Sorry if my question wasnt detailed enough.
I ended up doing this:
getcompanies: function() {
obj = this;
$.post('api/finder/result.php', {}, function(data) {
$.each(data.companies, function(i, item) {
obj.companies.push(item);
});
obj.loadcompanies();
}, "json");
},
loadcompanies: function() {
$.each(this.companies, function(i, item) {
alert(item.header);
}
}
I believe there is a issue with your server side code which is responsible for building JSON object which is getting returned via Ajax. The Correct JSON should be as follows:
{
"companies": [
{
"companyid": "115",
"saved": false,
"orgnumber": "010101010",
"companyname": "TestCompany",
"header": "header info"
},
{
"companyid": "116",
"saved": false,
"orgnumber": "010101010",
"companyname": "TestCompany",
"header": "header info"
}
]
}
Please note that there is only single key with name "companies" which holds an array of objects. Please correct your server side code to get such valid JSON. You can use free online JSON validator tools such as http://jsonlint.com/ to validate your JSON objects.
Now once you get such response from server; you just need to do following steps to get the companies array (following code will go into $.post success handler):
var jsonResp = JSON.parse(postResponse); //postResponse is the success resp of $.post
var companiesArray = jsonResp.companies;
$.each(companiesArray , function (index, valueObj){
var compId = valueObj.companyid;
var isSaved = valueObj.saved;
});
I hope this will help you a bit.
if you want to append new company into your companies array you should
var json_obj = {
"companies": [
{
"companyid": "115",
"saved": false,
"orgnumber": "010101010",
"companyname": "TestCompany",
"header": "header info"
},
{
"companyid": "116",
"saved": false,
"orgnumber": "010101010",
"companyname": "TestCompany",
"header": "header info"
} ]
};
//adding new company into your companies array
json_obj.companies.push({
"companyid":"117",
"saved" : false,
"orgnumber": "20120313",
"companyname":"anotherCompany",
"header":"another header info"
});
//if you want to loop through your companies list you can:
json_obj.companies.map(function ( obj ){
console.log(obj.companyid);
console.log(obj.companyname);
etc..
});
FormatSelection in select2Option removing data.
I am receiving my data in
$scope.superclasses = superclassDataList.data;
where superclassDataList is coming from service in angular.
Data i received from service is :
{
"data": [{
"name": "new Test",
"id": 4506898162253824,
"attendanceAllowed": true,
"subclasses": [{
"title": "HIN",
"children": null,
"entityName": "MyClass",
"entityId": 5136918324969472
},
{
"title": "ENG 101 A",
"children": null,
"entityName": "MyClass",
"entityId": 5699868278390784
}]
}
],
"success": true,
"errorMessage": ""
}
Code where i am applying my ng-grid to show this data:
<div ng-show="superclasses[row.rowIndex].edit"><div id="subclasses" ng-model="superclasses[row.rowIndex].subclasses" ui-select2="select2Options" data-placeholder="Add Subclasses" style="width:100%" multiple></div></div>
<div class="ngCellText" ng-class="col.colIndex()" style="display:inline" ng-show="!superclasses[row.rowIndex].edit" ng-repeat="subclass in superclasses[row.rowIndex].subclasses">{{subclass.title}} ,</div>
(I added one extra field "edit" in superclasses so don't be confuse with that. If it's true first div(Editable mode) will be visible else second(View mode))
Code for select2 i write is:
$scope.subclassNameFormat="";
$scope.select2Options = {
allowClear : true,
multiple: true,
width : 550,
minimumInputLength: 3,
query: function (query){
SuperclassService.getSubclassesUnassigned({searchTerm: query.term.toUpperCase()}, function(response) {
$scope.classesList = response.data;
var data = {
results: []
};
$.each($scope.classesList, function(){
if(this.list === undefined || this.list.length === 0) {
data.results.push({id: this.id, text: this.title,isApplied: false});
}
});
query.callback(data);
}, function(error){
console.log("Superclass is not deleted.... Please try again");
});
},
formatSelection: function format(state) {
if((state.title === undefined || state.title === "") && (state.text !== undefined && state.text !== "")){
$scope.subclassNameFormat = state.text;
}else if((state.text === undefined || state.text === "") && (state.title !== undefined && state.title !== "") ){
$scope.subclassNameFormat = state.title;
}
}
};
here getSubclassesUnassigned() method retrieve data from server on the basis of 3 character i entered to search: (minimumInputLength: 3),
Question: The data in $scope.superclasses comes from server is complete(JSON Data written above). And for a moment complete data of subclasses visible(when edit is false) (in this case name of subclasses HIN, ENG 101 A). Once it entered in "formatSelection" part of "$scope.select2Options" one data from "subclasses" array will be remove and it reflect on the "subclasses" column in grid (the code i write above) and show only one name (either "HIN" or "ENG 101 A"). I don't know why it get entered in "formatSelection" part of "select2options" because till data time "edit" field was false. (See in div code ng-show="!superclasses[row.rowIndex].edit" ). I don't know how it reflect the data. and even delete the data completely(2nd object of subclasses array.).
Have a same problem when value of div is in editable mode(ng-show="superclasses[row.rowIndex].edit") it only show one value of subclasses array.
data after passing control from FormatSelection:
{
"data": [{
"name": "new Test",
"id": 4506898162253824,
"attendanceAllowed": true,
"subclasses": [{
"title": "HIN",
"children": null,
"entityName": "MyClass",
"entityId": 5136918324969472
}]
}],
"success": true,
"errorMessage": ""
}
I tried everything from reading complete doc. about query and formatSelection from select2 but didn't find or understand anything, and also search on stackoverflow but didn't find any relevant link or didn't understand from those already on site. I know it might be silly question for some professionals but i started working on angular just 2 days ago.
Ask me in more explanation is required. I will try to provide everything that i know.
Thanks in advance.
PS: Please ignore My grammatical mistakes.
Try this code before "query :" in select2Option
initSelection: function(element, callback) {},
It will initialize your data for select2 which you are receiving in $scope.superclasses. It is working fine for me.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
i am trying to get a JSON and access its objects to retrieve data, all my paths seems to be working good but one specifically is not working. I just checked and the path is the same the other objects i am trying to access, in the console i keep getting undefined as a result. i will appreciate if you guys could tell me whats wrong with the code i will leave you the JSON structure and also the java Scripti hope you guys can help me figuring out, and also would be good if you could give me some tips on my coding because I am learning.
Java Script:
This function is called when you click on some item in a list.
function checkUser(){
console.log("clicked");
var user = $(this).html();
$.getJSON("js/options.json", function(json){
var itemsLength = json.chat.OnlineContacts.length;
for ( var i = 0; i < itemsLength; i++) {
var jsonUserName = json.chat.OnlineContacts[i].name;
var jsonUserStatus = json.chat.OnlineContacts[i].status;
var jsonUserAvatar = json.chat.OnlineContacts[i].avatar;
if(user == jsonUserName){
/*displayChatWindow(jsonUserName, jsonUserStatus, jsonUserAvatar);*/
console.log(jsonUserAvatar);
}
};
});
}
function displayChatWindow(user, status, avatar){
/*var template = _.template($("#windowTemplate").html(), {userName: user, userStatus: status, userAvatar: avatar});
$("body").prepend(template);*/
$(".messages-container").slimScroll({
height: '200',
size: '10px',
position: 'right',
color: '#535a61',
alwaysVisible: false,
distance: '0',
railVisible: true,
railColor: '#222',
railOpacity: 0.3,
wheelStep: 10,
disableFadeOut: false,
start: "bottom"
});
}
And this is the JSON:
{
"chat": {
"NumberOfOnlineContacts": "7",
"NumberOfOfflineContacts": "800",
"OnlineContacts": [
{
"name": "Nandy Torres",
"status": "online",
"avatar": "img/profile-picture2.jpg"
},
{
"name": "Catherine Varela",
"status": "Busy",
"avatar": "img/profile-picture3.jpg"
},
{
"name": "Jhonnatan Gonzalez",
"status": "online",
"avatar": "img/profile-picture4.jpg"
},
{
"name": "Juan Prieto",
"status": "away",
"avatar": "img/profile-picture5.jpg"
},
{
"name": "Alexander Barranco",
"status": "Busy",
"avatar": "img/profile-picture6.jpg"
}
],
"OfflineContacts": [
{
"name": "Nandy Torres"
},
{
"name": "Catherine Varela"
},
{
"name": "Jhonnatan Gonzalez"
},
{
"name": "Juan Prieto"
},
{
"name": "Jhonathan Sanchez"
}
]
}
}
When I try to do the console log on avatar like is in the example I just get undefined, but if i do console.log of name or status y just get the correct values.
Consider restructuring the original JSON object so you can access users directly by their unique id - in this case it appears to be "name".
For example:
{
"chat": {
"NumberOfOnlineContacts": "7",
"NumberOfOfflineContacts": "800",
"OnlineContacts": [
{
"Nandy Torres" : {
"status": "online",
"avatar": "img/profile-picture2.jpg"
}
},
{
"Catherine Varela" : {
"status": "Busy",
"avatar": "img/profile-picture3.jpg"
}
},
{...}
]
}
}
This could be accessed in the following ways without the expense of a loop:
json.chat.OnlineContacts[0].avatar
json.chat.OnlineContacts["Nandy Torres"].avatar
json.chat.OnlineContacts[user].avatar
There's an obvious cost-benefit here, but you may get the best of both by inlcuding the "name" attr as well:
"Nandy Torres" : {
"name": "Nandy Torres",
"status": "online",
"avatar": "img/profile-picture2.jpg"
}
And eventually moving to a more formal unique id:
"123abc" : {
"name": "Nandy Torres",
"status": "online",
"avatar": "img/profile-picture2.jpg"
}
There's lots of excellent ideas for structuring JSON at json.com
Jhonnatan, I'm glad you got your code working. So this isn't really an "answer" to your original question. But you also asked for tips on the coding and how to improve it. That's great that you're looking for ways to improve your code!
Here's one suggestion for you, a simpler way to write the checkUser() function. This is just a direct conversion of your function that should work with the same data format.
function checkUser() {
console.log( "clicked" );
var user = $(this).html();
$.getJSON( "js/options.json", function( json ) {
$.each( json.chat.OnlineContacts, function( i, contact ) {
if( user == contact.name ) {
displayChatWindow( contact.name, contact.status, contact.avatar );
console.log( contact.avatar );
}
});
});
}
Note how the use of the contact object makes it unnecessary to create all those jsonUserXxxx variables, because code like contact.avatar is just as simple and clear as jsonUserAvatar.
I also highly recommend #DaveRomero's excellent answer for a more strategic look at the question of how best to structure your JSON data.
More related reading: this discussion of JSON restructuring that I posted in response to this question earlier today.