Printing Ajax results in HTML - html

I have this J Query code:
$(document).ready(function(){
var $outData = $('#data');
var ajaxUrl = 'url.json';
$.ajax(
{
type: 'GET',
url:ajaxUrl,
success: function (result) {
console.log(result.passwords);
}
})
}
);
JSON file looks like this:
{
"passwords":[
{
"value":"tom",
"count":"432517"
},
{
"value":"anaconda",
"count":"454658"
},
{
"value":"111111",
"count":"148079"
},
What I need to do, is to print out each of these objects to be printed out in an ordered list (for instance it should look like this:
tom 432517
anaconda 454658
111111 148079
So far, nothing I have tried works. Althoug, I can console.log the entire object. Any suggestions?

Example rendering:
var $outData = $('#data');
var ajaxUrl = 'url.json';
$.ajax(
{
type: 'GET',
url:ajaxUrl,
success: function (result) {
result.passwords.forEach(pwd => $outData.append(`<div>${pwd.value} ${pwd.count}</div>`));
}
})
}
);

you can create elements and append to dom when you are done,
const data = {
"passwords": [{
"value": "tom",
"count": "432517"
},
{
"value": "anaconda",
"count": "454658"
},
{
"value": "111111",
"count": "148079"
}
]
}
const ol = document.createElement("ol");
for (const {
value,
count
} of data.passwords) {
const li = document.createElement("li")
li.innerText = `${value} -> ${count}`
ol.appendChild(li)
}
document.querySelector("#root").appendChild(ol)
<div id="root"></div>

Related

Access an axios data formatted as json from vue

I need to show data from a json response from get request. Vue part of my code is :
<script type="text/javascript">
var vm = new Vue({
el: '#app2',
delimiters: ['[[',']]'],
data: {
masa_data: {},
},
mounted: function() {
polling1=setInterval(function() {
axios.get('/order')
.then(function(response) {
vm.$data.masa_data = response.data;
})
}, 1000);
},
beforeDestroy () {
clearInterval(this.polling1)
}
});
</script>
masa_data comes from axios as below:
{ "Bahçe1": { "A": { "1": { "kisi_sayisi": "2", "siparisler": [ {
"adet": 2, "bolum": "drink", "satir": "Açık Çay" }, { "adet": 1,
"bolum": "tatli", "satir": "Kaymaklı Ekmek Kadayıfı" } ] },
When i want to show, for example, value of "kisi_sayisi", I could not figure out what to put inside html code below:
<p class="card-text">[[masa_data]]</p>
Try this.
<p class="card-text" v-if="Object.values(masa_data).length>0">[[masa_data.Bahce1.A['1']['kisi_sayisi'] ]]</p>
https://codepen.io/Pratik__007/pen/QWbjOxE?editors=1010

JSON variable block

I am having json template for elasticsearch query:
var getTemplate = function (agg, filter_term) {
var template = {
"size": 0,
track_total_hits: true,
query: {
bool: {
must: [
{
"query_string": {
"query": filter_term
}
},
aggs: {
"nested" : { "value_count" : { "field" : agg } },
agg: {
terms: {
field: agg,
size: 10,
order: {
"_count": "desc"
}
}
}
}
};
return template;
Sometimes, I want to skip the block with query_string so I want to pass in in the function call. So instead of this:
const callTerminated = agg_filter.getTemplate( 'bbbbb', 'aaa');
Do that:
const callTerminated = agg_filter.getTemplate( 'bbbbb', {"query_string": {"query": aaa }});
Or:
const callTerminated = agg_filter.getTemplate( 'bbbbb', "");
But how to change the template query? It wants comma after variable but when I skip query_string, I don't need comma.
New json template:
var getTemplate = function (agg, filter_term) {
var template = {
"size": 0,
track_total_hits: true,
query: {
bool: {
must: [
filter_term //here it wants comma
aggs: {
"nested" : { "value_count" : { "field" : agg } },
agg: {
terms: {
field: agg,
size: 10,
order: {
"_count": "desc"
}
}
}
}
};
return template;
So how to do it?

Postman responseBody JSON getting all the users

i am trying to create a runner in postman, but first i need to get all the usernames from some JSON, however i am having problems getting a list of all the usernames from the following JSON.
var data = JSON.parse(responseBody);
$.each(data.users, function (key, data) {
console.log(key);
});
{
"ok": true,
"users": {
"U02FJJD3M": {
"dnd_enabled": false
},
"U02FPPT59": {
"dnd_enabled": false
},
"U02FQENJU": {
"dnd_enabled": true
}
}
}
This will work.
var result = { "ok": true, "users": { "john": { "dnd_enabled": false, }, "sam": { "dnd_enabled": false, }, "sarah": { "dnd_enabled": true, } } };
var names = Object.keys(result.users);

ajax call and $.watch in Angular

I need to generate a select menu when a button is clicked. I am making an ajax call to get json data from external file, upon button click. which In turn should update the select with data from json. with the code below the select gets updated only after the button is clicked twice. I am watching the jsonData but its not working as expected.
HTML:
<div ng-controller="MainViewCtrl">
<button ng-click="getDeployedResources()"> Load Resources </button>
<select ng-model="selectedOption.name" ng-options="item.name as item.name for item in jsonData"></select>
</div>
json from dropdown.json:
{
"DeployedResources": {
"-env": "dev13",
"ResourceList": {
"-exportTime": 1444999007878,
"Resource": [{
"name": "default",
"type": "project"
},
{
"name": "System",
"type": "project"
},
{
"name": "StratusCommonServices",
"type": "project"
}]
}
}
}
JS:
var app = angular.module('JSONedit', ['ui.sortable'])
.controller('MainViewCtrl', ['$scope', '$http', '$filter','$compile', function ($scope, $http, $filter, $compile) {
$scope.jsonData = {};
$scope.getDeployedResources = function () {
$.ajax({
url: 'json/dropdown.json',
dataType: 'json'
}).done(function (data) {
$scope.jsonData = data.DeployedResources.ResourceList.Resource;
$scope.selectedOption = angular.copy($scope.jsonData[0]);
});
}
$scope.$watch('jsonData', function (json) {
$scope.jsonString = $filter('json')(json);
}, true);
$scope.$watch('jsonString', function (json) {
try {
$scope.jsonData = JSON.parse(json);
$scope.wellFormed = true;
} catch (e) {
$scope.wellFormed = false;
}
}, true);
}])
This is the correct life-cycle of a simple AngularJS Component!
Don't use jQuery for doing something that angular does better!
angular
.module('test', [])
.service('DataService', function($q, $http) {
var self = this;
var mock = {
id: 1,
"DeployedResources": {
"-env": "dev13",
"ResourceList": {
"-exportTime": 1444999007878,
"Resource": [{
"name": "default",
"type": "project"
}, {
"name": "System",
"type": "project"
}, {
"name": "StratusCommonServices",
"type": "project"
}]
}
}
};
self.load = function() {
console.log('loading data', mock.id);
for (var i = 0, len = mock.DeployedResources.ResourceList.Resource.length; i < len; i++) {
mock.DeployedResources.ResourceList.Resource[i].name += mock.id;
}
mock.id += 1;
return $q.when(mock);
return $http
.get('/api/data/')
.then(function(result) {
return result.data;
});
}
})
.controller('TestCtrl', function($scope, DataService) {
var vm = $scope;
vm.select = {
current: null,
items: []
};
vm.loadData = function(event) {
console.count('load data');
return DataService
.load()
.then(function(data) {
vm.current = data.id;
return data.DeployedResources.ResourceList.Resource;
})
.then(function(items) {
vm.select.items = items;
vm.select.current = vm.select.items[0];
})
};
vm.loadData();
});
.select-wrapper {
padding: 1em 2em;
background: yellow;
}
.select-wrapper select {
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<article ng-app="test">
<div ng-controller="TestCtrl">
<button type="button" ng-click="loadData($event);">LoadNew</button>
<div class="select-wrapper">
<select ng-model="select.current" ng-options="item as item.name for item in select.items"></select>
</div>
<div ng-bind="select.items | json"></div>
</div>
</article>

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.)