How I can order data pre date - javascript

I would like to know how I can do order data from API pre-date very time.
How its should be:
<table>
<tr>
<th>2017-02-17</th>
</tr>
<tr>
<td>some date</td>
<td>some date</td>
<td>some date</td>
</tr>
<tr>
<th>2017-02-15</th>
</tr>
<tr>
<td>some date</td>
<td>some date</td>
<td>some date</td>
</tr>
</table>
example:
URL API: http://api.tradingeconomics.com/calendar?c=guest:guest
My code:
$.ajax({
url: "url",
type: "Get",
datatype: "JSON",
contentType: "application/json",
error : function (data) { console.log("error:" + data) },
success: function (response) {
response.forEach(function (data) {
$('.top_table').append(
"<tr>" +
"<th>DATE</th>" +
"</tr>" +
"<tr id='content'>" +
"<td>some text....</td>" +
"<td>some text....</td>" +
"<td>some text....</td>" +
"<td>some text....</td>" +
"</tr>"
);
});
console.log(response);
}
});
But its print like:
date
result
date
result
How I can do it?

I don't know if I've understood your question very well, but I think that could give you some tips.
Your API returns an Array of Objects if you make and Ajax GET request, so you can order this Array before inserting the content into the DOM:
The next example order the data in descending order comparing the Date parameter, there is another date parameter called LastUpdate, I don't know if you want to use it in your logic.
$.get("https://api.tradingeconomics.com/calendar?c=guest:guest", function (data) {
//---Order the array received from the server
data.sort(function (a, b) {
return (new Date(a.Date)) - (new Date(b.Date));
});
//---The data is ordered, you can insert it into the DOM
});
In the other hand, your code inserts a row with the header content and a row with the body content in each iteration, this is not correct. You need to add all the header texts in a single row and each item of the Array needs to be inserted in separated rows.
Here you have a working example to give you an idea of the process:
https://jsfiddle.net/elchininet/ym8qp415/
EDIT: Seeing your comments, I understand now that you want to grouping the data not just ordering it. I recommend you to use the reduce method of the Array class to create a new data separated by dates and after that you can insert the data in the table:
var regdate = /^(\d{4}\-\d{2}\-\d{2})T(\d{2}:\d{2}:\d{2})$/;
//---Sort the data from the server
data.sort(function (a, b) {
return (new Date(a.Date)) - (new Date(b.Date));
});
var group = data.reduce(function (before, current) {
var day = current.Date.replace(regdate, "$1");
var hour = current.Date.replace(regdate, "$2");
if (!before[day]) {
before[day] = [];
}
current.Hour = hour;
before[day].push(current);
return before;
}, {});
//---The data is ordered and grouped, you can insert it into the DOM
Working example with fake data (Because of the example in the API returns only one day):
http://jsfiddle.net/elchininet/nvv4fnon/

Without a plugin, this is going to be difficult to achieve unless the "calendar" information is pulled from a database, it may be worth sorting in PHP, loading and displaying the data in jQuery
<script type="javascript">
$(function() {
$("BODY").on("click", "TH[data-orderby]", function() {
var order = $(this).data("orderby") || "date";
var parent = $(this).parents("table").parent();
$.ajax({
url: 'calendar?c=guest:guest',
data: 'order-by=' + URLEncode(order),
type: 'POST',
success: function(response) {
parent.html(response);
},
error: function(event, request, settings) {
console.warn("Ajax Error", request);
}
})
});
});
</script>
<div class="parent">
<table>
<thead>
<tr>
<th>Heading</th>
<th data-orderby="date">Date</th>
<th>Title</th>
<th data-orderby="last_updated">Last Updated</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data</td>
<td>Data</td>
<td>Data</td>
<td>Data</td>
</tr>
</tbody>
</table>
Because we use $("BODY").on("click", "TH[data-orderby]"), even when the data is reloaded from the server, the sort functionality will remain.
I hope this helps.

Related

How do i refresh or redraw table rows

Below is the classical issue which I am facing during my app development.
I have an array of JSONObjects in my spring controller that I have to iterate in the jsp;
Also another status attribute called JSONArrayStatus is set that suggests if JSON array is empty or not.
Using jquery if JSONArray is empty I will show noDataImageDiv otherwise will show tableDIV (Binding the data from JSONArray using JSTL)
The problem I am facing is as below.
1. Edit a row in the table and click on Update. At this time I make an Ajax Call say, "UpdatedUser", which will return all the records along with the updated records. I could use refresh however thats not a recommended user experience and hence a no no.
To reflect the updated users in the table, I use jquery as below
clearing table rows table.clear().draw()
Loop the result set as follows.
redraw code
function reDrawExternalContactUsers(externalUsers) {
table.clear().draw();
var row = "";
$.each(externalUsers, function (i, field) {
row = '<tr><td></td><td></td><td class="edit">edit</td></tr>';
$("#tableDIV").append(row);
});
}
afetr this redraw or refresh process
This function is NOT working
$(".edit").click(function(){
});
This function is working
$("#tableDIV .edit").click(function(){
});
Suggest a better way of refreshing table rows, if any.
<div id="tableDIV">
<table id="tableID">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
if data exist
loop{
<tr>
<td></td>
<td></td>
<td class="edit">edit</td>
</tr>
} // loops ends
if close
</tbody>
</table>
</div>
<div id="noDataImageDiv"> No data image</div>
html code :
<div id="tableDIV">
<table id="tableID">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
if data exist
loop{
<tr>
<td class="user-name"></td>
<td></td>
<td class="edit" data-user-id="">edit</td> //set user_id in attr data-user-id
</tr>
} // loops ends
if close
</tbody>
</table>
</div>
<div id="noDataImageDiv"> No data image</div>
jquery code :
you should use click event on document
$(document).on('click', '.edit', function () {
var btn = $(this);
var user_id = btn.attr("data-user-id"); //user_id of user will update
// extra user data
$.ajax({
method: "POST",
url: url,
data: {
'id': id,
// extra data to send
},
success: function (data) {
if (data.status) // successfully user updated
{
var user = data.user;
/* you can set user data like this */
btn.closest('tr').find('.user-name').html(user.name);
}
}
});
});

Ajax call returns Object(object), how to get the value from it

JSP file
<div class="container">
<table id="headerTable" class="table table-bordered">
<thead>
<tr>
<th colspan="2">Header</th>
</tr>
</thead>
<tbody>
<c:forEach items="${headerList}" var="field">
<tr>
<th>${field}</th>
<td><input id="${field}" type="text" class="form-control "></td>
</tr>
</c:forEach>
</tbody>
</table>
Javascript
$('#parseBtn').click(function() {
var parseMsg = $('#msgText').val();
alert("parse message is " + parseMsg);
$.ajax({
type: "GET",
url: "/parseMessage",
data: {
"msg": parseMsg
},
success: function(data) {
//data format looks like Object {SubsystemChannel: "F", MessageNumber: "200257", DebugQueue: " ", WorkStationNumber: "023", FrontEndNumber: "0000"…}
$('#headerTable input').each(function() {
var id = $(this).attr('id');
var field = data.id;
$(this).val(field);
});
}
});
});
What I am going to do is, go through the $('#headerTable input'), set the value(from data) in it. So, I get the each input id first, then get the value from data using id, but it failed.... Could you help me on this? thank you very much
You should use Bracket notation instead of dot notation to access properties using id variable
$('#headerTable input').each(function () {
var field = data[$(this).attr('id')];
$(this).val(field);
});

read html table content from remote website using java script

I want to read html table data from remote website and store in a list or array using java script. If I have html like the one below from a remote website:
<!DOCTYPE html>
<html>
<body>
<table style="width:100%">
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
</body>
</html>
I want to get table data and store it to an array i.e
index 0 index 1 index 2
array=| Jill Smith 50 | Eve Jackson 94| John Doe 80 |
var result;
function xmlparser() {
$.ajax({
type: "GET",
url: "http://www.example.com",
dataType: "html",
success: function (data) {
result = data.table;
alert(result);
},
}
});
}
I wanted alert( alert(result) ) to display table with the content-assuming the html above is from http://www.example.com.
var result = []; // Create empty array
$("tr").each(function(i, el) { // iterate through all TR elements
result.push(el.innerText.replace(/\t/g, " "));
// no need to get each element and concat,
// innerText will do it if you replace tabs for spaces
});
console.log(result); // ["Jill Smith 50", "Eve Jackson 94", "John Doe 80"]
http://jsfiddle.net/etLdmzt3/

Creating table from API

My function is pulling information from an api and then putting it into the table. For some reason this function is not working.
this is my function:
function getPayInfo(socCode) {
var apiurl = "http://api.lmiforall.org.uk/api/v1/ashe/estimatePay?soc=";
var apicall = apiurl + socCode;
$.get(apicall, function(data) {
$("#Pay tbody").html("");
$.each(data.years, function(i, e) {
var tablerow = $("<tr></tr>");
tablerow.append("<td>" + e.year + "</td>");
tablerow.append("<td>" + e.estpay + "</td>");
$("#Pay tbody").append(tablerow);
});
});
}
and this is the table I am putting it into:
<div class="well table table-stripped">
<h4>Pay Information</h4>
<h5>Pounds per Week</h5>
<table id="Pay">
<thead>
<tr>
<th>Year</th>
<th>Estimate Pay</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
I expected it to return a year and data value into the table. if you take the url in the function and add a certain 4 figure value (the socCode) (e.g. 5113) to the end it will give the data online this should then be returned to the table body.
Have you debugged/examined the data structure inside your $.get callback? It looks to me that your access method is incorrect. When I access your example url, I get the following data back:
{
"soc":5113,
"series":[
{
"year":2012,
"estpay":340
}
]
}
I think you want your iterator to be this instead:
// there is no data.years
$.each(data.series, function(i, e) {
...
This should make your e param be of the form {year: 2012, estpay: 340}, which appears to be what you want to interpret it as.

Dynamic table column update by id, done right?

I am kinda new to Ajax/Json so I would like to know if the following is at least near to the best practice. The goal is to update specific columns (in this case quantity and price) of a table every x seconds.
I got a HTML table defined like this:
<table id="#edition_table>
<tbody>
<tr>
<td class="name">Lightning Bolt</td>
[...]
<td class="qty">2</td>
<td class="price">$4.99</td>
<tr>
<tr>
<td class="name">Fireball</td>
[...]
<td class="qty">0</td>
<td class="price">$0.07</td>
<tr>
[...]
</tbody>
</table>
And a JS function defined like this:
function edition_update(edition)
{
var table_rows = $('#edition_table').find('tbody tr td.name a');
$.ajax({
type: 'GET', url: 'ajax_edition_update.php', data: { edition : edition }, dataType: 'json',
success: function(json_rows)
{
var new_qty, new_price;
table_rows.each(function(index) {
var td_id = $(this).attr('href').replace('?card=', '');
for (i in json_rows) {
if (json_rows[i].card_id == td_id)
{
new_qty = json_rows[i].qty;
new_price = json_rows[i].low_price;
break;
}
}
var parent_tr = $(this).parent().parent();
parent_tr.find('td.qty').text(new_qty);
parent_tr.find('td.price').text(!isNaN(new_price) ? '$' + new_price : new_price);
});
}
});
setTimeout(edition_update, 30000, edition);
}
The PHP file returns a JSON including card_id, qty and low_price.
This does work fine. I guess I could set up a data-id=[card_id] on the class=name td to get rid of the .replace, but that kinda blows up the html footprint as the id is already present.
The real question is whether any performance improvements (especially regarding the two loops) are possible or necessary? The target number of rows per table is arround 500 and the content and order is totally dynamic/unpredictable, of course.

Categories