Issues parsing JSON with JQuery/Ajax - javascript

I'm accessing an API through JQuery/JSON. I can get the entire JSON block to display on a page using the following:
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
contentType: 'application/json',
headers: {'Access-Control-Allow-Origin': '*'},
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', 'Basic ' + btoa('un:pw'));
},
error: function(jqXHR, textStatus, data){
console.log("(1)Static error message");
console.log("(2)Output of textStatus " + textStatus);
console.log("(3)Output of data " + data);
},
success: function(data) {
var myData = data;
$('#myData').html('<p>'+ myData +'<p>')
}
})
However, when I try to access a key/value from that JSON, I get undefined. I think I'm not parsing the JSON correctly. Here's an example of some code I tried inside the success function:
$.each(myData.blockOne, function(data){
$('#myData').html('<p>'+ this.blockOne.id +'<p>')
});
Here's is an example of the JSON:
[
{
"ItemName": {
"id": "XYZ",
"caseNumber": "123"
},
"blockOne": [
{
"id": "ABC",
"subject": "321",
}
],
"blockTwo": [
{
"id": "EFG",
"subject": "456",
}
]
},
{
"ItemName": {
"id": "HIJ",
"caseNumber": "333"
},
"blockOne": [
{
"id": "JIL",
"subject": "999",
}
],
"blockTwo": [
{
"id": "OPE",
"subject": "778",
}
]
},
]
I'm trying to output something like the following:
Item
ID: XYZ
Case: 123
Block 1:
ID: ABC
Subject: 321
Block 2:
ID: EFG
Subject: 456
Item
ID: HIJ
Case: 333
Block 1:
ID: JIL
Subject: 999
Block 2:
ID: OPE
Subject: 778
Any help is greatly appreciated.

Inside $.each(), you need to loop through myData array instead of myData.blockOne because myData.blockOne returns only the data of the blockOne object.
var myData = [{
"ItemName": {
"id": "XYZ",
"caseNumber": "123"
},
"blockOne": [{
"id": "ABC",
"subject": "321",
}],
"blockTwo": [{
"id": "EFG",
"subject": "456",
}]
},
{
"ItemName": {
"id": "HIJ",
"caseNumber": "333"
},
"blockOne": [{
"id": "JIL",
"subject": "999",
}],
"blockTwo": [{
"id": "OPE",
"subject": "778",
}]
},
];
var html = "";
$.each(myData, function() {
html += `
<p>Item</p>
<p>ID :${this.ItemName.id}</p>
<p>Case :+${this.ItemName.caseNumber}</p>
<p>Block 1:</p>
<ul>
<li>ID :${this.blockOne[0].id}</li>
<li>Subject :${this.blockOne[0].subject}</li>
</ul>
<p>Block 2:</p>
<ul>
<li>ID :${this.blockTwo[0].id}</li>
<li>Subject :${this.blockTwo[0].subject}</li>
</ul>
`
});
$('#myData').html(html)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myData"></div>

Related

select2 I don't want to get data out of json

My script won't load any data in the Select2. I made data from laravel controller with response JSON data, this result json
"results": [
{
"id": 1,
"code": "11",
"name": "jackson",
},
{
"id": 2,
"code": "12",
"name": "michael,
},
this my script code
$('.name_user').select2({
width: "100%",
placeholder: "Search...",
ajax: {
url: "{{route('name_user')}}",
processResults: function(data) {
return {
results: $.map(data, function(obj) {
return {
id: obj.id,
name: obj.name
};
})
};
},
cache: true
}
});
How do I get data from route name_user?

Angular material chips md-autocomplete not working on ng-repeat

I using Angular 1.5.5, and angular-material 1.1.0 here.
When I adding md-chips in ng-repeat loop it do not working, I got follow error:
angular.js:13550 TypeError: this.items.some is not a function
at e.appendChip (http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.js:13:28477)....
md-template do not what that should (as return i go value from md-item-text, which is _id, but i need $chip.text);
it don't addind an item even if i changing md-item-text="item.text" (which is wrong but for test).
It do working well for a single item (with out ng-repeat).
<md-list-item ng-repeat="i in dialogueItems track by $index">
<md-chips ng-model="i.text" md-removable="true" md-enable-chip-edit="true" md-autocomplete-snap="true" md-require-match="true">
<md-autocomplete md-min-length="0" md-match-case-insensitive="true" md-selected-item="i.selectedItem" md-search-text="i.searchText" md-items="item in loadItems(i.searchText, i.tagId)" md-item-text="i.selectedItem._id" md-autoselect="true" md-no-cache="true"
placeholder="Words">
<span md-highlight-text="i.searchText">{{item.text}}</span>
</md-autocomplete>
<md-chip-template>
{{$chip.text}}
</md-chip-template>
</md-chips>
</md-list-item>
JS
$scope.dialogueItems = [{
tagId: 1,
text: [],
searchText: null,
selectedItem: null
}];
$scope.loadItems = function(query, tagId) {
return $http({
method: 'POST',
url: '/api/wordsapi/searchwords',
data: {
text: query,
tagId: tagId,
count: 10
}
}).then(function(d) {
return d.data.words;
});
};
And example of api result:
{
"words": [{
"text": "you",
"_id": "030423b3-99ed-42a2-bab7-7efd10a68cfa"
}, {
"text": "i",
"_id": "a833abe2-c602-4cd7-b765-5b14229ecc7d"
}, {
"text": "god",
"_id": "724766b6-c83c-4679-bf28-827ad1a516eb"
}, {
"text": "a",
"_id": "c2b7920b-7541-42f1-9b61-84a1d7c42930"
}, {
"text": "bless",
"_id": "6ea9b56f-b47b-4453-b97c-0b5ba4311992"
}, {
"text": "am",
"_id": "ab12f90d-9b40-4e33-af13-14e75fbb405a"
}, {
"text": "your",
"_id": "55910a38-4435-4db4-8498-6cddaf4b0059"
}, {
"text": "with",
"_id": "7c5a2627-777f-443e-9f58-83c62e4fae11"
}, {
"text": "are",
"_id": "befa650c-e894-477b-9e67-2f7fb24e40b5"
}, {
"text": "good",
"_id": "90ee8243-630f-4f91-9ecf-0a6469716e0d"
}],
"allCount": 1024
}

JSGrid Not show data from json

Hi I'm tryng to modify the "DataManipulation" example from jsGrid demos and I'm not able to show data from a json file retrived using a GET ajax call. Here's my controller code:
{
loadData: function (filter) {
var data = $.Deferred();
$.ajax({
type: "GET",
contentType: "application/json",
url: "myFileURL.json",
dataType: "json"
}).done(function(response){
console.log(response);
data.resolve(response);
});
return data.promise();}
The json retrived is like this
{"98762":{"Address":"Address 1","Age":1,"Country":1,"Married":false,"Name":"Name1"},"637399":{"Address":"Address 2","Age":2,"Country":2,"Married":true,"Name":"Name 2"},"234567554":{"Address":"Address 3","Age":3,"Country":3,"Married":true,"Name":"Name"}}
Your json is not well formed. jsGrid expects a list of objects as a return type. Use this instead.
[
{
"Address": "Address 1",
"Age": 1,
"Country": 1,
"Married": false,
"Name": "Name1"
},
{
"Address": "Address 2",
"Age": 2,
"Country": 2,
"Married": true,
"Name": "Name 2"
},
{
"Address": "Address 3",
"Age": 3,
"Country": 3,
"Married": true,
"Name": "Name"
}
];
This is with the assumption that the schema of the json is correct. Good luck!

Print all mongoDB data to string nodejs

I have a sample mongo document like this:
> db.chat.find().pretty()
{
"_id": ObjectId("555f1c0c7f4b820758b439b0"),
"user": "Guest1",
"friend": [{
"userfriend": "Guest2",
"noidung": [{
"method": "send",
"date": "2015-05-22T19:11:34+07:00",
"content": "allloooo"
}, {
"method": "receive",
"date": "2015-05-23T09:08:14+07:00",
"content": "yes man"
}]
}, {
"userfriend": "Guest3",
"noidung": [{
"method": "send",
"date": "2015-05-23T15:42:34+07:00",
"content": "foo 15:42"
}, {
"method": "receive",
"date": "2015-05-23T15:42:45+07:00",
"content": "bar 15:43"
}]
}]
}
And in my server.js, i use this code to print all data:
var chathistory = db.collection('chat');
chathistory.find().toArray(function (err, docs) {
console.log(docs)
});
And i get this log in my terminal:
[ { _id: 555f1c0c7f4b820758b439b0,
user: 'Guest1',
friend: [ [Object], [Object] ] } ]
'friend' field doesn't print all, its only [Object], so how can i get full data.
To print all the data, use the JSON.stringify() method
db.collection('chat').find().toArray(function(err, docs) {
console.log(JSON.stringify(docs));
});

Modify JSon format returned by an Ajax request

I have a JQuery plugin where I have the following:
transformResult: function(response, originalQuery) {
}
Inside this function I need to convert the originalQuery Json data:
[
{ "Id": 4, "Title": "Title 4" },
{ "Id": 2, "Title": "Title 2" }
]
Into the response Json data format:
{
suggestions: [
{ data: "4", value: "Title 4" },
{ data: "2", value: "Title 2" }
]
}
Id is the data and Title is the value.
How can I do this?
Thank you,
Miguel
var arr =[
{ "Id": 4, "Title": "Title 4" },
{ "Id": 2, "Title": "Title 2" }
]
var obj = {suggestions : []};
$.each(arr, function(i, o) {
obj.suggestions.push({name : o.Id, value : o.Title});
});
FIDDLE

Categories