Using API result to create another request and display them together - javascript

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>");
})
})
});

Related

sending html data to view and then sending to controller to update sql database

I have a HTML table where one of the columns value is dynamically added. I have an update button, upon clicking it I want this data to get updated in my sql database. For this, I am planning to first fetch the table data and put into view , then send data to controller and then updating sql.
I am stuck at the first step,
Descibing table below
<thead>
<tr>
<th>ID</th>
<th >Name</th>
<th>Active</th>
<th>Order By</th>
</tr>
</thead>
<tbody>
#if (ViewBag.data != null)
{
foreach (var item in ViewBag.data)
{
<tr>
<td >#item.AutoID</td>
<td #item.Text</td>
<td >#item.Active</td>
<td>#item.OrderBy</td>
</tr>
}
}
</tbody>
</table>
</div>
</div>
<input type="submit" value="Update Preference" class="BtnUpdOrderId" />
</div>
I tried this below js function to fetch the data
$(".BtnUpdOrderId").click(function () {
var tr = $(this).closest('tr');
var id = tr.find('input[name="autoid"]').val();
var text = tr.find('input[name="text"]').val();
var active = tr.find('input[name="active"]').val();
var orderby = tr.find('input[name="orderby"]').val();
alert('type1 : ' + id + ' ' + text + ' ' + active + ' ' + active);
});
but not sure why nothing came in alert
var TableData = new Array();
$('#tblLookup1 tr').each(function (row, tr) {
TableData = TableData + $(tr).find('td:eq(0)').text();
alert(TableData);
});
then tried the above block of code to get data in a variable but still not able to get anything.
Once I get the data I can try sending from view->controller.
So need the following help:
what mistake am I making?
once this is fixed, how to send data to sql? (this is a ado.net based mvc project)
you might want to consider creating a json object:
Creating json object in mvc and returning from controller
then build your table Convert JSON array to an HTML table in jQuery
finally, the update need only post back the json object
https://dontpaniclabs.com/blog/post/2013/02/27/posting-json-data-to-an-mvc-controller-via-ajax/
if you going to use this jason object make sure you use serialization
https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-6-0
your have to patch these concepts together but there are a lots of tutorials and examples online so it be a good learning experience
I hope this helps
helpful links:
https://www.sqlshack.com/modifying-json-data-using-json_modify-in-sql-server/
Updating a JSON object using Javascript
https://www.geeksforgeeks.org/how-to-convert-json-data-to-a-html-table-using-javascript-jquery/
create json object from html table using selected colums using jquery

Make each new item created in a list (each one with a different ID) execute a certain function automatically

I explain myself: I have a Sharepoint custom list and I'm using AngularJS to call this list. With the data I obtain from the list, I'm making a "single bar chart" for each item in this list. I'm using jquery.lineProgressbar.js to make the charts.
I'm doing the table with ng-repeat. And I need to provide a different ID name to each "chart div", otherwise the jquery.lineProgressbar.js won't work. Here's my HTML:
<table>
<tr>
<td>Name</td>
<td>Productivity percentage</td>
</tr>
<tr ng-repeat="item in items">
<td>{{item.Name}}</td>
<td>
<!-- The "ng-attr-id" provides the div a different ID depending the name they introduce. i.e.: "chart-Person1" -->
<div ng-attr-id="{{'chart-' + item.Name}}" data-percentage="{{item.Productivity_x0020_percentage}}"></div>
</td>
</tr>
</table>
and my main problem, the SCRIPT:
<script>
//I need to call each chart, one by one like this:
chartFunction('chart-Person1');
chartFunction('chart-Person2');
chartFunction('chart-Person3');
chartFunction('chart-Person4');
//and I need to make this automatically,
//because people will submit new items whenever they want,
//and I can't be updating the script each time someone uploads something.
function chartFunction(elementID) {
var dataPercentage = $("#" + elementID).data('percentage');
//this calls the chart code
$("#" + elementID).LineProgressbar({
//it says that the div selected will have a "percentage" equals to the percentage they wrote in the list.
percentage: dataPercentage
});
}
</script>
I have a Plunker. It is a little different because it has a function which runs the charts only when they're in the viewport, and it doesn't use AngularJS. But it's only so you can see how it works: my Plunker
So, as I said in my code, I need to call each new element added to the sharepoint list, but I can't be creating new calls in my code each time someone uploads an item. Thanks in advance for your help.
I've found the solution to this.
I needed to do it directly in the call of the list (in the Angular code).
<script>
var myApp = angular
.module('myApp', [])
.controller('myController', function ($scope, $http) {
//first I call the Sharepoint List with AngularJS
$http({
method: 'GET',
url: "SiteURL/_api/web/lists/getByTitle('Employees List')/items?$select=*",
headers: { "Accept": "application/json;odata=verbose" }
}).then(function onSuccess(response) {
//If the call is successful I create an empty Array called "peopleArray"
//Here I will store the names of the divs which will run the chart's code
$scope.items = response.data.d.results;
var theItems = $scope.items,
peopleArray = [];
//I run a loop to go through all the items in the Sharepoint list
//I assign a name for each person in the "peopleArray"
for(var i=0; i<theItems.length; i++) {
var currentItem = theItems[i];
peopleArray.push('chart-' + currentItem.Name);
};
//I run another loop, this one goes through the "peopleArray"
//each item executes the function below with the div name assigned in the previous loop
for(var z=0; z<peopleArray.length; z++) {
chartFunction(peopleArray[z]);
}
//and this is the function to make the charts for each person
function chartFunction(elementID) {
var dataPercentage = $("#" + elementID).data('percentage');
$("#" + elementID).LineProgressbar({
percentage:dataPercentage
});
}
}).catch(function onError(response) {
//In case of Error, it will pop an alert
alert("Error! The charts can't be loaded.");
});
});
</script>

Make a query with JSON

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");
});
});

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.

How to get data of all rows from a dynamically generated table by jQuery

I'm using jQuery and django
I have a dynamic table generated by jQuery, which holds the email field and password field and the delete button that could remove the row:
$("button#genBtn").click(function() {
var t = $("input#inputEmail").val();
var p = $("input#inputPassword").val();
var delBtn = $('<button class=\"btn btn-danger\">delete</button>');
var row = $("<tr><td>" + t + "</td><td>" + p + "</td><td></td></tr>");
$('td:last', $(row)).append(delBtn);
$(delBtn).bind("click", deleteNode);
$("table tbody").append(row);
});
This is the table:
<table class="table table-striped">
<thead>
<tr>
<th>email</th>
<th>password</th>
<th>action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Let say I'd like to get the data of all rows from this table, and post it to sever side. How could I do that?
Without any additional libraries, something like this:
(1) get the data from the table
function getTableData()
{
// Array of data we'll return
var data = [];
// Counter
var i = 0;
// Cycle through each of the table body's rows
$('tbody tr').each(function(index, tr) {
var tds = $(tr).find('td');
// Check we've got two <td>s
if (tds.length > 1) {
// If we do, get their text content and add it to the data array
data[i++] = {
email: tds[0].textContent,
password: tds[1].textContent
}
}
});
return data;
}
(2) post it to the server
$.ajax({
method: 'post',
url: '', // Set the URL of whatever in Django will handle your post
data: getTableData()
});
However, if I were attempting this task, I would achieve (1) by using Knockout, which would allow for a much better separation between view and viewmodel (or between template and view, you might think of them, as a Django user). Great that you're using a decent server-side framework, would be a pity to end up with spaghetti code on the client!

Categories

Resources