Ordering JSON data in a table - javascript

I am creating a "leaderboard" page as an external component to a Facebook game.
Basically the app is passing me data through a given JSON response file ('score.json' which contains data objects with three keys: Name, Team, Score), and I am parsing this into an HTML table using the code below:
$(document).ready(function(){
$.getJSON("score.json",
function (data) {
var tr;
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + data[i].User_Name + "</td>");
tr.append("<td>" + data[i].score + "</td>");
tr.append("<td>" + data[i].team + "</td>");
$('table').append(tr);
}
});
});
What I need to do:
Display these table rows in descending order based on the "score" value.
Add a "rank" column with a dynamically generated number inserted with each row
I am just a beginner with JavaScript so any help would be much appreciated.
EDIT: Solved. Final code below:
$(document).ready(function(){
$.getJSON("score.json",
function (data) {
var tr;
data.sort(function(a,b) { return parseFloat(b.score) - parseFloat(a.score) } );
var rank = 1;
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + rank + "</td>");
tr.append("<td>" + data[i].User_Name + "</td>");
tr.append("<td>" + data[i].score + "</td>");
tr.append("<td>" + data[i].team + "</td>");
$('table').append(tr);
rank = rank +1;
}
});
});

you can use this to sort your array :
json.sort(function(a,b) { return parseFloat(b.score) - parseFloat(a.score) } );
Here is the jsFiddle.

Related

Javascript producing random arrays with random numbers in it?

I am doing a simple assignment for class, and am trying to create a table using just Javascript. I have my table perfectly set up, it's just that every other row it shows a random number, and then skips to the next. how can I get rid of the random row?
var table = ["Name", "Turn Average", "Surface Area", "100% Boosting"];
var names = ["Octane", "Dominus", "Breakout", "X-Devil", "Batmobile"];
var turnaverages = [2.18, 2.22, 2.22, 2.21, 2.25];
var surfacearea = [34495, 34529, 32679, 34242, 34365];
var maxboost = [1.967, 2.031, 2.035, 2.014, 2.10];
function info() {
document.write("<table>");
document.write("<tr>");
//these next lines output the table heading (th) tags for the table (this information doesn't repeat in the table)
document.write("<th>Name</th>");
document.write("<th>Turn Average</th>");
document.write("<th>Surface Area</th>");
document.write("<th>100% Boosting</th>");
document.write("</tr>"); //close first table row element
//create a for loop that will last for the number of days in the forecast
for(var i = 0; i < names.length; i++){
document.write("<tr>"); //create a table row
//output each table data tag for the table with information pulled
from the arrays
document.write("<td>" + names[i] + "</td>");
document.write("<td>" + turnaverages[i] + "</td>");
document.write("<td>" + surfacearea[i] + "</td>");
document.write("<td>" + maxboost[i] + "</td>");
document.write("</tr>");
//depending on the description of the weather for the day, change
the image to be representative to that description -- (for
example on a rainy day, show the rainy image)
if ( names[i] === "Dominus" ) {
document.write("<td>" + turnaverages[i] + surfacearea[i] +
maxboost[i] + "</td>");
}
else if ( names[i] === "Breakout" ){
document.write("<td>" + turnaverages[i] + surfacearea[i] +
maxboost[i] + "</td>");
}
else if ( names[i] === "X-Devil" ){
document.write("<td>" + turnaverages[i] + surfacearea[i] +
maxboost[i] + "</td>");
}
else if( names[i] === "Batmobile" ){
document.write("<td>" + turnaverages[i] + surfacearea[i] +
maxboost[i] + "</td>");
}
document.write("</tr>"); //close the table row element
}
document.write("</table>"); //close the table element
}
You have
document.write("<td>" + maxboost[i] + "</td>");
document.write("</tr>");
followed immediately by weather tests that attempt to write tds, followed again by another
document.write("</tr>"); //close the table row element
So, you just need to delete the first </tr>, since you don't actually want to close the row yet:
var table = ["Name", "Turn Average", "Surface Area", "100% Boosting"];
var names = ["Octane", "Dominus", "Breakout", "X-Devil", "Batmobile"];
var turnaverages = [2.18, 2.22, 2.22, 2.21, 2.25];
var surfacearea = [34495, 34529, 32679, 34242, 34365];
var maxboost = [1.967, 2.031, 2.035, 2.014, 2.10];
function info() {
document.write("<table>");
document.write("<tr>");
//these next lines output the table heading (th) tags for the table (this
document.write("<th>Name</th>");
document.write("<th>Turn Average</th>");
document.write("<th>Surface Area</th>");
document.write("<th>100% Boosting</th>");
document.write("</tr>"); //close first table row element
//create a for loop that will last for the number of days in the forecast
for (var i = 0; i < names.length; i++) {
document.write("<tr>"); //create a table row
//output each table data tag for the table with information pulled
document.write("<td>" + names[i] + "</td>");
document.write("<td>" + turnaverages[i] + "</td>");
document.write("<td>" + surfacearea[i] + "</td>");
document.write("<td>" + maxboost[i] + "</td>");
//depending on the description of the weather for the day, change
if (names[i] === "Dominus") {
document.write("<td>" + turnaverages[i] + surfacearea[i] +
maxboost[i] + "</td>");
} else if (names[i] === "Breakout") {
document.write("<td>" + turnaverages[i] + surfacearea[i] +
maxboost[i] + "</td>");
} else if (names[i] === "X-Devil") {
document.write("<td>" + turnaverages[i] + surfacearea[i] +
maxboost[i] + "</td>");
} else if (names[i] === "Batmobile") {
document.write("<td>" + turnaverages[i] + surfacearea[i] +
maxboost[i] + "</td>");
}
document.write("</tr>"); //close the table row element
}
document.write("</table>"); //close the table element
}
info();
The 2.22345292.031 and similar numbers are a result of string cocatenation - when you take a string and + to it, you will end up with another string. (not sure what you actually want there instead)

Getting values from an api call

Hi all i have a url with returns values (https://api.sunrise-sunset.org/json?lat=35.857368&lng=14.477653). I would like to get the values of sunset and sunrise. The code I am trying is the following but for some reason nothing is happening. Seems that I cannot access 'second level'
$.getJSON('https://api.sunrise-sunset.org/json?lat=35.857368&lng=14.477653', function (data) {
var tr;
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + data[i].results[0].sunrise + "</td>");
tr.append("<td>" + data[i].sunset + "</td>");
$('table').append(tr);
}});
Can someone please help me? thanks
Neither the response object nor .results is an array - remove the array indicies.
const tr = $('tr');
$.getJSON('https://api.sunrise-sunset.org/json?lat=35.857368&lng=14.477653', function (data) {
console.log(data.results.sunrise + ' :: ' + data.results.sunset);
tr.append("<td>" + data.results.sunrise + "</td>");
tr.append("<td>" + data.results.sunset + "</td>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table><tr></tr></table>

Pass checkbox values to server

This is my function to get some data from a database table and put checkboxes a page.
function myfunction() {
var dataObject = {};
$.ajax({
url: "http://localhost:45217/api/Symptom/LoadSymptom",
type: "GET",
data: JSON.stringify(dataObject),
contentType: "application/json",
success: function (response) {
for (var i = 0; i < response.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + response[i].SymptomName + "</td>");
tr.append("<td>" + "<input type=checkbox tr.id=" + i + " value=" + i + ">" + "</td>");
$('table').append(tr);
}
}
});
}
How I pass this checkbox values to server.
http://api.jquery.com/jquery.post/
$.post( "YourServerPageToProcessData.php", function( dataToSendToServer ) { /* client action on success or error here */ });
-- have you tried that?
In order to make an Ajax request each time user clicks on checkbox, you can do that in 2 ways-
Define function you want to perform onClick-
function someFn() {
// perform some Ajax request
}
Method 1:
for (var i = 0; i < response.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + response[i].SymptomName + "</td>");
tr.append('<td><input type=checkbox id="' + i + '" value=' + i + ' onclick="someFn()"></td>');
$('table').append(tr);
}
Method 2:
$('input[id^="symptom_chkbox_"]').on('click', function(){
// perform some Ajax request
})
for (var i = 0; i < response.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + response[i].SymptomName + "</td>");
tr.append('<td><input type="checkbox" id="symptom_chkbox_' + i + '" value=' + i + '></td>');
$('table').append(tr);
}

How to sum Total JSON Results?

i have this script to take data from JSON Results, also this script filter results by ID
$(document).ready(function () {
//Call EmpDetails jsonResult Method
$.getJSON("/smetkis/getTrosokList",
function (json) {
var tr;
for (var i = 0; i < json.length; i++) {
if (json[i].skID == '#Html.DisplayFor(model => model.smID)') {
tr = $('<tr />');
tr.append("<td >" + json[i].Artikal + "</td>");
tr.append("<td>" + json[i].kol + "</td>");
tr.append("<td>" + json[i].cena + "</td>");
tr.append($('<td class="vkupno1">' + json[i].vkupnot + '</td>'));
$('table').append(tr);
}
}
});
});
Also i have this script sor SUM Of column with class vkupno1, but not understand the results from cell.
$(document).ready(function () {
colSum();
});
function colSum() {
var sum = 0;
$(".vkupno1").each(function () {
sum += parseFloat($(this).text());
});
$('#result').html((sum).toFixed(2).replace(/(\d)(?=(\d{6})+(?!\d))/g, "$1.") + " €");
}
How to sum (json[i].vkupnot)-value or cell classed "vkupno1"
here is JSON Results:
[{"smetki":null,"trId":1,"skID":1,"Artikal":"gdfgsdgfdg","kol":4.00,"cena":4.00,"vkupnot":16.00},{"smetki":null,"trId":4,"skID":4,"Artikal":"kjhkjhkjhk","kol":7.00,"cena":7.00,"vkupnot":47.00},{"smetki":null,"trId":5,"skID":4,"Artikal":"lkjlkjlk","kol":8.00,"cena":8.00,"vkupnot":64.00},{"smetki":null,"trId":6,"skID":5,"Artikal":"gdfg","kol":5.00,"cena":5.00,"vkupnot":25.00},{"smetki":null,"trId":7,"skID":6,"Artikal":"gdfg","kol":5.00,"cena":5.00,"vkupnot":25.00},{"smetki":null,"trId":8,"skID":7,"Artikal":"gagaggag","kol":5.00,"cena":55.00,"vkupnot":275.00},{"smetki":null,"trId":9,"skID":7,"Artikal":"ggg","kol":4.00,"cena":65.00,"vkupnot":260.00}]
You can add the values from response itself without reading from DOM.
Try this
$(document).ready(function() {
//Call EmpDetails jsonResult Method
$.getJSON("/smetkis/getTrosokList",
function(json) {
var tr;
var sum = 0; //initialising sum
for (var i = 0; i < json.length; i++) {
if (json[i].skID == '#Html.DisplayFor(model => model.smID)') {
tr = $('<tr />');
tr.append("<td >" + json[i].Artikal + "</td>");
tr.append("<td>" + json[i].kol + "</td>");
tr.append("<td>" + json[i].cena + "</td>");
tr.append($('<td class="vkupno1">' + json[i].vkupnot + '</td>'));
$('table').append(tr);
sum += parseFloat(json[i].vkupnot); //adding directly from the response
}
}
$('#result').html((sum).toFixed(2).replace(/(\d)(?=(\d{6})+(?!\d))/g, "$1.") + " €");
});
});
And you need to wait for the response before reading the dynamically created DOM elements.

How to make sure another (new) page is not shown when submitting a form

For an assignment I need to have a table made up of JSON data gotten from a server through an AJAX GET request. Also I have to have an extra row to be able to fill in some extra data as well, this data has to be added to the server where I make the AJAX GET request from, I do this by using an AJAX POST request. Both things I have been able to do, so I now have a table which shows the data from the server which you can also add data to as well. But the problem is that when I click the 'submit' button another page will load showing a new URL made for the added data to the server. I only want to add the data to the table, without opening a new page. I have seen some answers on this with <form> tags, but since I have to use a <form> tag I can not use another one inside.
How is this possible by using a <input> tag and button?
This is the code in HTML I have for the row to fill in your own data.
<tr>
<td rowspan="1" colspan="1">
<input type="text" name="name" placeholder="Name" required="">
</td>
<td rowspan="1" colspan="1">
<input type="text" name="category" placeholder="Category" required="">
</td>
<td rowspan="1" colspan="1">
<input type="number" name="amount" min="1" placeholder="Amount" required="">
</td>
<td rowspan="1" colspan="1">
<input type="text" name="location" placeholder="Location" required="">
</td>
<td rowspan="1" colspan="1">
<input type="date" name="date" min="2000-01-02" required="">
</td>
</tr>
</tfoot>
</table>
<input type="submit" value="Submit" id="submit">
</form>
And this is the code in JavaScript for adding the data from the server to the table:
$(function func(json) {
var url = '%url%'
$.ajax({
type: "get",
url: '%url%',
dataType: "jsonp",
});
$.getJSON(url,
function(data){
var tr;
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + data[i].name + "</td>");
tr.append("<td>" + data[i].category + "</td>");
tr.append("<td>" + data[i].amount + "</td>");
tr.append("<td>" + data[i].location + "</td>");
tr.append("<td>" + data[i].date + "</td>");
$('#table_one').append(tr);
}
});
});
I hope I have provided enough information, and thanks in advance for the help :)
EDIT:
I edited the code to solve this, now it looks like this:
var url = '%url%
var tabinithtml = '';
function fillTable() {
$('#table_one').html(tabinithtml);
$.getJSON(url,
function(data){
var tr;
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + data[i].name + "</td>");
tr.append("<td>" + data[i].category + "</td>");
tr.append("<td>" + data[i].amount + "</td>");
tr.append("<td>" + data[i].location + "</td>");
tr.append("<td>" + data[i].date + "</td>");
tr.sort
$('#table_one').append(tr);
}
});
}
function insertRecord() {
$.post( url, $( "#form" ).serialize()
);
}
$( document ).ready(function() {
tabinithtml = $('#table_one').html();
fillTable();
$('#form').submit(function(e) {
e.preventDefault();
insertRecord();
fillTable();
return false;
});
});
You have to prevent form submission by using
$("form").submit(function(){ return false; });
Just add
return false;
before the function ends
For example:
function(){
//all function srcripts
return false;
}
In your case, it should be like this:
function(data){
var tr;
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + data[i].name + "</td>");
tr.append("<td>" + data[i].category + "</td>");
tr.append("<td>" + data[i].amount + "</td>");
tr.append("<td>" + data[i].location + "</td>");
tr.append("<td>" + data[i].date + "</td>");
$('#table_one').append(tr);
return false;
}
you can make sure the form doesn't actually submit to "url given" by preventing the default behavior, but you'll have to do whatever you want with the form using js/jquery
$('#form').submit(function(e){
e.preventDefault();
//do your stuff here
$.ajax(){
url: '%url%',
method: 'POST',
data: {datafromform}
}.success(msg){
console.log(msg)
}
})
try something like this, you get echo JSON data on the server side, so in PHP for the results you add:
echo $jsonizedData;
die();
so in message, now you will have the json data back from the php file
I have been able to solve this by using this code:
var url = '%url%
var tabinithtml = '';
function fillTable() {
$('#table_one').html(tabinithtml);
$.getJSON(url,
function(data){
var tr;
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + data[i].name + "</td>");
tr.append("<td>" + data[i].category + "</td>");
tr.append("<td>" + data[i].amount + "</td>");
tr.append("<td>" + data[i].location + "</td>");
tr.append("<td>" + data[i].date + "</td>");
tr.sort
$('#table_one').append(tr);
}
});
}
function insertRecord() {
$.post( url,
$( "#form" ).serialize()
);
}
$( document ).ready(function() {
tabinithtml = $('#table_one').html();
fillTable();
$('#form').submit(function(e) {
e.preventDefault();
insertRecord();
fillTable();
return false;
});
});

Categories