Make a query with JSON - javascript

I have JSON data gets Vedios data of youtube list. And the following link display structure of my JSON.
<a href="https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=UUbW18JZRgko_mOGm5er8Yzg&key=AIzaSyDGm1uzuqPPUGzG-qN7u6gTaS8ApXBJYvw">
Click me to get all list videos ID ...
</a>
And here is the channel with its ID
After analyses of my JASON, I have JSON array named "items" (row 9).
Now all I need to get specific information from all units included with this array "items".
All I need to make a query using JavaScript or c# to return JSON with this specific data
title
description
thumbnails - standard
videoId

Finally, I found a solution for my problem. Not very professional but good for now.
I used Jquery selectors to extract data from my JSON object as following.
$(document).ready(function () {
var jsonLink = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=PL0zTBP9-UnPaIurxKLr3rfPZwHrFl2mEq&key=AIzaSyDGm1uzuqPPUGzG-qN7u6gTaS8ApXBJYvw&maxResults=50";
$.getJSON(jsonLink).done(function (data) {
var items = [];
$.each(data.items, function (i, item) {
items.push("<li>" + item.snippet.title + "</li>");
if (i === 5) {
return false;
}
});
$("<ul/>", {
"class": "my-new-list",
html: items.join("")
}).appendTo("body");
});
});

Related

Get all data from gridmvc including all paging in javascript?

I am trying to fetch data from gridmvc and show graphs using chart.js its working fine but issue is that its showing just with pages. Because i have enabled paging in grid and when i click on next page then next grid data page graphs show, but i want to show graph of complete grid data includes all pages.
<div class="panel-body">
#await Html.Grid(Model).Columns(columns =>
{
columns.Add(c => c.ID).Titled("StudentID").Filterable(true);
columns.Add(c => c.Name).Titled("Name").Filterable(true);
columns.Add(c => c.Major).Titled("Major").Filterable(true);
columns.Add(c => c.Minor).Titled("Minor").Filterable(true);
columns.Add(c => c.Email).Titled("Email").Filterable(true);
columns.Add(c => c.Address).Titled("Address").Filterable(true);
columns.Add(c => c.GPA).Titled("GPA").Filterable(true);
}).Searchable(true, false, true).WithPaging(10).ChangePageSize(true).Sortable(true).EmptyText("No data found").Named("GridSearch").RenderAsync()
</div>
Javascript
function LoadChart() {
debugger;
var chartType = parseInt($("#rblChartType input:checked").val());
var items = $(".grid-mvc").find(".grid-table > tbody").children();
var json = [];
$.each(items, function (i, row) {
$col1=$(row).children()[0].innerText;
$col2 = $(row).children()[1].innerText;
$col3 =$(row).children()[2].innerText;
$col4 =$(row).children()[3].innerText;
$col5 =$(row).children()[4].innerText;
$col6 =$(row).children()[5].innerText;
$col7 =$(row).children()[6].innerText;
json.push({ 'StudentID': $col1, 'Name': $col2, 'Major': $col3, 'Minor': $col4, 'Email': $col5, 'Address': $col6, 'GPA': $col7
})
// Map JSON values back to label array
var labels = json.map(function (e) {
return e.Name;
});
console.log(labels); // ["2016", "2017", "2018", "2019"]
// Map JSON values back to values array
var values = json.map(function (e) {
return e.GPA;
});
var chart=BuildChart(labels, values, "Students Name by GPA");
I want to show graphs which include complete data in gridmvc not just on current page.
but issue is that its showing just with pages. Because i have enabled
paging in grid and when i click on next page then next grid data page
graphs show, but i want to show graph of complete grid data includes
all pages.
var items = $(".grid-mvc").find(".grid-table > tbody").children();
var json = [];
$.each(items, function (i, row) {
$col1=$(row).children()[0].innerText;
$col2 = $(row).children()[1].innerText;
$col3 =$(row).children()[2].innerText;
$col4 =$(row).children()[3].innerText;
$col5 =$(row).children()[4].innerText;
$col6 =$(row).children()[5].innerText;
$col7 =$(row).children()[6].innerText;
json.push({ 'StudentID': $col1, 'Name': $col2, 'Major': $col3, 'Minor': $col4, 'Email': $col5, 'Address': $col6, 'GPA': $col7
})
The issue relates the above scripts, since you implement paging, when using the above code to get the table resource, it only gets the current page records, then display the page grahps.
To solve this issue, you could get the records from the page model (Model) or create an action method to get all records, then, use JQuery Ajax method to call this method and get the grid data.
To get records from the page model, in your Asp.net Core MVC application, you could use the Json.Serialize() method to convent the Model to JSON string first, then use JSON.parse() method convent the JSON string to JavaScript Object, then loop through the Object and get all data.
Code like this (Index.cshtml)
#model List<StudentViewModel>
#section Scripts{
<script>
$(function () {
LoadChart();
});
function LoadChart() {
debugger;
//var chartType = parseInt($("#rblChartType input:checked").val());
//var items = $(".grid-mvc").find(".grid-table > tbody").children();
var json = [];
var items = JSON.parse('#Json.Serialize(Model)');
$.each(items, function (index, item) {
json.push({ 'StudentID': item.id, 'Name': item.name, 'Major': item.major, 'Major': item.major, 'Email': item.email, 'Address': item.address, 'GPA': item.gpa });
});
//show graphs based on the json array.
The screenshot like this:

How to map the JSON response to Html page using ng-repeat

I am trying to map the data received in the JSON to my html page using the ng-repeat, but somehow its not producing the data on the front end.my html code is as follows:
ul ng-repeat="ScheduleData in viewScheduleData"<br/>
li{{ScheduleData.day}}<br/>
ul<br/>
li{{ScheduleData.time_start}}/li<br/>
li{{ScheduleData.time_end}}/li<br/>
/ul<br/>
/li <br/>
/ul<br/>
and my scheduleCtrl.js has the code as follows:
Schedule.viewSchedule($scope.doctorprofile,function(data) {<br/>
console.log(JSON.stringify(data));<br/>
if (data.ResponseCode == 1) {<br/>
console.log("yes in");<br/>
$Scope.viewScheduleData = data.Result;<br/>
}});
I can see thee data coming through JSON stringify
Try with these
Schedule.viewSchedule($scope.doctorprofile,function(data) {
if (data.ResponseCode == 1) {
$scope.viewScheduleData = data;
}});
$Scope needs to be changed to $scope. "s" should be small.
You need to give like this.and viewScheduleData should be an array.
<ul> ng-repeat="ScheduleData in viewScheduleData">
<li>{{ScheduleData.day}}</li>
<li>{{ScheduleData.time_start}}</li>
<li>{{ScheduleData.time_end}}</li>
</ul>

Using API result to create another request and display them together

I'm having trouble retrieving some data from an API, the server provides JSON data as follows:
http://segue-api.fisl16.softwarelivre.org/api/rooms/1/slots
http://segue-api.fisl16.softwarelivre.org/api/talks/526 (the number is the talk id)
I need to create a table to visualize the data that is relevant to me. So I created a simple JS function to retrieve information from the first link (/rooms/1/slots) and feed an HTML table (the code is below).
Using the ID I can gather from the first function I want to make another request to the API (/talks/"id") and display the results on the same row as the ID.
The final result would be the table from the snippet with a new column called "description" which contains the description available on the API (/talks/"id") on the same row as the "id".
I'm clueless, any ideas?
var room1 = "http://segue-api.fisl16.softwarelivre.org/api/rooms/1/slots"
$.getJSON(room1,function(data){
$.each(data.items, function(){
$("#table").append("<tr><td>"+this['begins']+"</td><td>"+this['talk'].id+"</td><td>"+this['duration']+"</td><td>"+this['talk'].title+"</td><td>"+this['talk'].owner+"</td><td>"+this['talk'].coauthors+"</td><td>"+this['room_name']+"</td>");
});
});
table, th, td {
border: 1px solid black;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<table id="table">
<th>Data e Hora</th>
<th>Id</th>
<th>Duração</th>
<th>Título</th>
<th>Palestrante</th>
<th>co-palestrantes</th>
<th>sala</th>
</table>
If you can not get the data from the second API for many ID at once, it can be in a loop to make subqueries ( http://jsfiddle.net/tmjvzo63/ ):
room1 = "http://segue-api.fisl16.softwarelivre.org/api/rooms/1/slots";
$.getJSON(room1,function(data){
$.each(data.items, function(){
var rid = "r"+this['talk'].id;
$("#table").append("<tr id='"+rid+"'></tr>");
$("#"+rid).append("<td>"+this['begins']+"</td><td>"+this['talk'].id+"</td><td>"+this['duration']+"</td><td>"+this['talk'].title+"</td><td>"+this['talk'].owner+"</td><td>"+this['talk'].coauthors+"</td><td>"+this['room_name']+"</td>");
var rj = "http://segue-api.fisl16.softwarelivre.org/api/talks/"+this['talk'].id;
$.getJSON(rj,function(data){
console.log(data.resource.id);
$("#r"+data.resource.id).append("<td>"+data.resource.full+"</td>");
});
});
});
You could do something like
$.getJSON(room1,function(data){
$.each(data.items, function(){
var row = item;
$.getJSON("http://segue-api.fisl16.softwarelivre.org/api/talks/" + item["talk"].id, function(dataItem){
var $table = $("#table");
if ($table.find("th:last").text() !== "Description") { //Or whatever it is named
$table.find("th:last").after("<th>Description</th>"); //This creates the TH if it doesn't exist
}
$table.append("<tr><td>"+item['begins']+"</td><td>"+item['talk'].id+"</td><td>"+item['duration']+"</td><td>"+item['talk'].title+"</td><td>"+item['talk'].owner+"</td><td>"+item['talk'].coauthors+"</td><td>"+item['room_name']+"</td><td>" + dataItem.description + "</td>");
})
})
});

Table must have clickable cells to display more options from XML file

I need to have a clickable cell within a table, so it will show a description of a TV show. I have it feeding in the XML to make the table called 'tvGuide1' and a tooltip like function shows a brief description. The XML create the first row with the first 5 elements within XML.
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "MonWedSatXML.xml",
cache: false,
success: function(xml){
$(xml).find('#1, #2, #3, #4, #5, #6, #7, #8, #9, #10, #11, #12, #13, #14, #15, #16').each(function(){
var Time = $(this).find('Time').text();
dcs1 = $(this).find('Desc1').text();
dcs2 = $(this).find('Desc2').text();
dcs3 = $(this).find('Desc3').text();
dcs4 = $(this).find('Desc4').text();
dcs5 = $(this).find('Desc5').text();
var Program1 = $(this).find('Title1').text();
var Program2 = $(this).find('Title2').text();
var Program3 = $(this).find('Title3').text();
var Program4 = $(this).find('Title4').text();
var Program5 = $(this).find('Title5').text();
$('<tr></tr>').html('<th>'+Time+"</th><td Title='"+dcs1+"' <div onClick='info()'>"+Program1+"</td><td Title='"+dcs2+"'<div onClick='info()'>"+Program2+"</td><td Title='"+dcs3+"'<div onClick='info()'>"+Program3+"</td><td Title='"+dcs4+"'<div onClick='info()'>"+Program4+"</td><td Title='"+dcs5+"'>"+Program5+'</td>').appendTo('#tvGuide1');
});
}
});
$( "#tvGuide1" ).on("click","td", function(e){
console.log('hello');
$("#myModal").modal("show");
});
});
</script>
XML EXAMPLE
<Programs>
<TVShows id="1">
<Time>08:00</Time>
<Title1>Breakfast</Title1>
<Desc1>The latest news, sport, business and weather from the team. Also in HD. [S] Including regional news at 25 and 55 minutes past each hour.</Desc1>
<Title2>Fake Britain</Title2>
<Desc2>Matt Allwright investigates the activities of conmen, revealing the fake high-EndTimesome farmers' markets and looking at counterfeit bike parts.</Desc2>
<Title3>Family Guy</Title3>
<Desc3>Hilarious show about a modern family</Desc3>
<Title4>ITV News</Title4>
<Desc4>Your latest news, sport and weather</Desc4>
<Title5>Homes Under the Hammer</Title5>
<Desc5>People buy rubbish houses and give them a make over then sell them</Desc5>
</TVShows>
'<table id="tvGuide1">
<tr>
<th>Time 24hr Clock</th>
<th>BBC 1<img src="Channel1.png" style="width:150px;height:150px"></th>
<th>BBC 2<img src="Channel2.png" style="width:150px;height:150px"></th>
<th>Comedy Central<img src="ComedyCentral.png" style="width:150px;height:150px"></th>
<th>ITV<img src="Channel3.jpeg" style="width:150px;height:150px"></th>
<th>Channel 4<img src="Channel4.jpg" style="width:150px;height:150px"></th>
</tr>
</table>'
The problem the XML will create the table and pull in the data but I have no idea how to implement the modal to display the description from the XML
Any help would be great.
You could add the information you want to display in the modal as data-attributes to each <td> - e.g. like this:
<td data-desc="Hilarious show about a modern family">Family Guy</td>
and either add a class to each clickable <td> or check on click if this data-attribute is set:
$("td").on("click", function (e) {
e.stopPropagation();
if($(this).data("desc")){
modal($(this).data("desc"));
}
});
with either a self written modal function or an existing solution. As example I've just created a Fiddle with a simple modal function and set the data for the first three entries. In case you have more information that you want to display in the modal, this can be added as another data-attribute. This is only an example, as you already have set the short description as title-tag I suppose there's an additional longer description in the XML that you would like to only display in a modal.
For reference: http://api.jquery.com/data/
Update: For the mentioned requirement to get the description for the modal from the XML on click on td - following approach:
function loadXml(item) {
$.ajax({
type: "GET",
url: 'programs.xml',
dataType: "xml",
success: function (xml) {
parseXml(xml, item);
}
});
}
function parseXml(xml, item) {
var $xml = $(xml),
desc = $xml.find(item).text();
modal(desc);
}
function modal(desc) {
$("body").addClass("inactive");
$("#modal").text(desc).show();
}
$(document).ready(function () {
$(".programm td").on("click", function (e) {
e.stopPropagation();
var col = $(this).parent().children().index($(this));
if (col > 0) {
loadXml("Desc" + col);
}
});
$("body").on("click", function (e) {
if (!$("#modal").is(e.target)) {
$("#modal").hide();
$("body").removeClass("inactive");
}
});
});
Adjusted but not working Fiddle - not working because the XML (even if referenced as absolute URL) wouldn't be readable from there because of CORS. The XML has to be on the same domain as the page that's reading the XML, so for testing purposes I've just uploaded it on a testserver and it's working, using an absolute URL to the XML as well as using the relative URL when the XML is next to the HTML.
As explanation - each tr has the class programm, on click of an td with an index > 0 (as the first td with index 0 is the time) calls the function loadXml() with desc + index of the clicked td as parameter. On success, parseXml() is called, retrieves the text of the description (e.g. Desc2) and calls the modal() function with the retrieved text.
I've only written this as an example for the XML you provided, as you will have more entries, e.g. for the next time slot under <TVShows id="2">, you can adjust this to take the number/index of the clicked tr with class programm into account.

Dojo: dijit.form.filteringselect dynamically add options from Json

I am getting data from json file, now i want to add it to filteringselect. i tried below code but its not adding, please help me
HTML code==
<select data-dojo-type="dijit/form/FilteringSelect"
id="education"></select>
Javascrip code==
request.get("/json/education.json", {
handleAs: "json"
}).then(function(data) {
var node = dijit.byId('education');
dojo.forEach(data.items, function(desc, index){
node.addOption({
label: desc.name,
value: desc.value
});
});
},
function(error){});
Json code
{
"title":"Education",
"items":[
{"name":"Select Education","value":"0"},
{"name":"B.A", "value":"1"},
{"name":"B.Sc" ,"value":"2"},
...........................
The store of FilteringSelect can be set dynamically, based on the ajax call.
var str = new dojo.store.Memory(optionData);
dijit.byId('widgetId').set('store',str);
But, your json data must be like this:-
var optionData={
data:[
{id:'aaaaaa',name:'aaaaaa'},
{id:'bbbbbb',name:'bbbbbb'}
]
};
The above example will actually replace the store. If, the new data from ajax call need to be appended to the existing options, then
//str is the existing store of FilteringSelect field above
dojo.forEach(result.data, function(optionSet, index){
str.add(optionSet);
});
Note to remember: 'addOption' is available only for Select. Not for FilteringSelect.
I hope this helps:
dijit.byId("select_id").store.root.add(dojo.create("option",{ value: "some", innerHTML: "label of option"}));
To remove the existing elements did just that:
var size = dijit.byId("select_id").store.root.removeChild.length;
for(var i=size; i>=0; i--){ dijit.byId("select_id").store.root.removeChild(dijit.byId("select_id").store.root.children[size-1]);
}

Categories

Resources