Rendering DB values using Javascript - javascript

Till date in a project of mine there has been straight forward implementation of DB normalization and the way "status codes" are stored , for example
Patient_table
patientId | referralStatus
1001 1
1002 2
Referral_status_codes_master
refStatusCode | refValue
1 Pending
2 Awaiting
Joining these two tables gives appropriate data for "STATUS_CODES" .
My intent here is , would it be appropriate if i use Javascript to achieve this for relatively small Master table values , i.e which don't change at all , like status here for example .
let's say i load patient data in a HTML table as it is and by using javascript i change their meanings .
<tr>
<td>1001</td>
<td>1</td>
</tr>
Objective : Intead of using join in sql query , obtain same results using Javascript on client side.
and i bind that HTML table to a JS function and change status 1 to "Pending", i know it's possible ,my Question is :
What are the disadvantages of doing it .
Are there any Libraries already existing for this very purpose only.
Please provide your suggestions .
Thank you

Since you have finite number of statuses, you can map values to user friendly name and than just replace them using js/jQuery
var statusMap = {
'1': 'Normal',
'2': 'Missing',
'3': 'Dead',
};
$(document).ready(function () {
$('[data-status]').each(function () {
$(this).html(statusMap[$(this).data('status')]);
})
});
table {
width: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>Name</th>
<th>Status</th>
</tr>
<tr>
<td>John Wick</td>
<td data-status="2"></td>
</tr>
<tr>
<td>Abraham Lincoln</td>
<td data-status="3"></td>
</tr>
<tr>
<td>Dummy User</td>
<td data-status="2"></td>
</tr>
</table>
statusMap can be generated from PHP side by doing json_encode({All values from Referral_status_codes_master});

Related

How can I split the following string into an array that I can use to populate a html table

I have a string that looks like:
var str = '{ "abc": {
"decline_reason": "Business rule switched off"
},
"def": {
"decline_reason": "No response by interface"
},
"ghi": {
"decline_reason": "Requested incorrect size" }';
I would like to split that string into an array that I can use to populate a table on a webpage. I intend to use the initial reference ('abc'), with the reason ('Business rule switched off') on row 1, initial reference ('def'), with the reason ('No response by interface') on row 2, etc...
I have tried regex to break it down, and I've managed to find one that removes quotes, but not to break the string down.
I intend to populate the table with code like:
<table id="declinesTable">
<tr>
<th onclick="sortTable(0)">Reference Code</th>
<th>Decline Reason</th>
</tr>
<tr id="lender1">
<td id="lender1"><script>document.getElementById("lender1").innerHTML = declines[0];</script>
</td>
<td id="declineReason1"><script>document.getElementById("declineReason1").innerHTML = declines[2];</script>
</td>
</tr>
</table>
skipping out the value "decline_reason" from the table.
Any suggestions?
Couple of things - your string is missing a final }. Not sure where you're getting the string from, but it's in JSON format, so use JSON.parse to get it into an object, then iterate over the object to do something with each individual nested object. I would strongly recommend using a library like jQuery to help you append it to the table. You can google and very quickly find out how to add jQuery to your project. See below.
function stringParse(str) {
const json = JSON.parse(str);
const html = Object.entries(json).reduce((h, [k, v]) =>
h += `<tr><td>${k}</td><td>${v.decline_reason}</td></tr>`
, "");
$('#declinesTable').append(html);
}
const str = '{ "abc": {"decline_reason": "Business rule switched off"},"def": {"decline_reason": "No response by interface"},"ghi": {"decline_reason": "Requested incorrect size"}}'
stringParse(str);
<table id="declinesTable">
<tr>
<th>Reference Code</th>
<th>Decline Reason</th>
</tr>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Web Scraping Using data-title and Without Using Classes or Ids

I am trying to scrape a website the issue is that the specific elements do not have Classes or Ids, but they do have data-tile. I need help referring to these when I am choosing an element to scrape.
Here is the html that I am scraping.
<div data-v-1234567z="">
<table data-v-1234567z="" align="center">
<thead data-v-1234567z="">
<tr data-v-1234567z="">
<th data-v-1234567z="">User</th>
<th data-v-1234567z="" style="cursor: pointer;">Money</th>
<th data-v-1234567z="" style="cursor: pointer;">Watch Time (minutes)</th>
</tr>
</thead>
<tbody data-v-1234567z="">
<tr data-v-1234567z="">
<td data-v-1234567z="" data-title="User" class="user-cell">
<span data-v-821a25a2="" data-v-1234567z="" class="mini-user-display">
<img data-v-821a25a2="" src="https://image.com" class="mini-user-profile-image" />
<span data-v-821a25a2="" class="mini-user-name">user1234</span>
</span>
</td>
<td data-v-1234567z="" data-title="Money">100,000</td>
<td data-v-1234567z="" data-title="WatchTime">678</td>
</tr>
</tbody>
</table>
</div>
I need to scrape the Money, WatchTime, and username.
Here is the code that I am using for the scraper.
async function pageFunction(context) {
const $ = context.jQuery;
const results = [];
$('tbody').each(function() {
results.push({
userName: $(this).find(".mini-user-name").text(),
watchTime: $(this).find("data-title-watchTime").text()
});
});
return results;
}
There are many issues with this code the userName actually does return the usernames the issue is that there is no break in between all the names and it's just one big blob.
The other bigger issue is that I can't get any data back from watchTime, this is because I can't figure out how to properly select the WatchTime data-title in JavaScript.
I have looked for a few hours and I can't figure it out.
To get an element by data-attribute in JQuery you just call it like you would in CSS, watchTime in your case would be called like this:
watchTime: $(this).find('[data-title="WatchTime"]').text()
As for your code coming out as one blob you are pushing objects to an array, until you do something to iterate over your array of objects and convert them to a readable format it will just be a blob of data. Without seeing what is calling this function and how you're handling the returned data it's impossible to provide much assistance with that.
EDIT:
Here's an example of how you might want to return your data using template literals for a more readable output.
const results = [];
$('tbody').each(function() {
results.push(
`Username: ${$(this).find(".mini-user-name").text()}
WatchTime: ${$(this).find('[data-title="WatchTime"]').text()}
Money: ${$(this).find('[data-title="Money"]').text()}`
);
});
return results;
This would give an output like:
Username: user1234
WatchTime: 678
Money: 100,000

How to read a list of html tables in JavaScript

I have a list of HTML tables given by pandas data frame in the format of:
list_html =
[<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>score</th>
<th>id</th>
<th>name</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>0.776959</td>
<td>grade</td>
<td>grade</td>
</tr>
<tr>
<th>1</th>
<td>0.414527</td>
<td>class</td>
<td>class</td>
</tr>, ... , ... ]
I am trying to visualize this data in an html page and could not do it. I do not have enough experience in web development. My goal is to use JavaScript to loop through each item the list and visualize them below each other in html. It would be great if anybody can help!
This is what I tried so far, its probably completely wrong:
var list_html = list_html // list of html codes as a javascript variable.
var arrayLength = analysis.length;
for (var i in list_html) {
document.getElementById("analysis_1").innerHTML = list_html[i];
}
Given a valid array of strings list_html (actually list_html is not a valid array of strings, since the markup in each entry is not wrapped in quotes) and a container in the DOM with id "analysis_1" it's simply a matter of:
var container = document.getElementById('analysis_1');
for (var i = 0; i < list_html.length; i++) {
container.innerHTML += list_html[i];
}
UPDATE:
well... in your scenario there is no need at all for a loop, you can simply inject a single string by joining the elements in the array:
document.getElementById('analysis_1').innerHTML = list_html.join('');
fast and simple! :)
using jquery's selectors :
Give the 'td' which contains the data a class name, eg: 'MyTd';
Select them all: $(.MyTd).text()
Done!

AngularJS - Ng-Table won't parse headers

Using Ng-table, I have tried to create one table view, that could be controlled from AngularJS parameters.
To control the header text, I need to put it in data-title or ng-data-title (Example: data-title="'Test'")
But, it always makes the table header empty.
Instead of filling it:
Code Snippet:
<td ng-repeat="v in tableSettings.data" data-title="v.name">
{{v.data?v.data(row):row[v.id]}}
</td>
Full Code:
<table ng-table="table" class="table" show-filter="{{tableSettings.filter}}">
<tr ng-repeat="row in $data">
<td ng-repeat="v in tableSettings.data" ng-click="tableSettings.click(row)" ng-attr-data-title="'{{v.name}}'"
ng-if="v.type!='switch'"
sortable="'{{sortable?sortable:v.id}}'">
{{v.data?v.data(row):row[v.id]}}
</td>
</tr>
</table
When I try to parse Angular into it, I just get errors: (press to see the errors)
"'{{v.name}}'" "{{v.name}}"
Is there a way to fix it, or even to parse it manualy from AngularJS?
Ok the problem is that the data-title attribute is meant to be used with static text (well known columns) such as data-title="'My first column'"
If what you need is dynamic columns you got to use the ng-table-dynamic directive.
For example:
<table ng-table-dynamic="tableParams with cols" show-filter="true" class="table table-bordered table-striped">
<tr ng-repeat="row in $data track by row.id">
<td ng-repeat="col in $columns">{{::row[col.field]}}</td>
</tr>
</table>
Take notice in the directive declaration uses a special syntax tablePrams with cols. Here the cols is a $scope variable that must follow the following schema for this to work properly.
$scope.cols = [
{ title: 'ID', field: 'id', filter: { id : 'text' }, show: true, sortable: 'id' },
{ title: 'Installation', field: 'installationAt' },
...
];
Title and field are mandatory whereas filter, show, sortable depend on your usage scenario.
You can play around with this code pen

jquery table selector with condition

i had a table that submitted from my jquery append script, are its possible to find the match value with jquery selectors,
i want to check if the condition >= var $minimumEducation, it will pass to next page when submit, i set the value 0 for High School, 1 for Diploma and so on as it use selectbox, the var $minimumEducation variable come from my php admin, anyone knows how to pass this condition ? thanks
<thead>
<tr>
<th>Name</th>
<th>Relation</th>
<th>DOB</td>
<th>Education</th>
<th>Job</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Uncle</td>
<td>02/19/1955</td>
<td>Bachelor</td>
<td>Carpenter</td>
</tr>
<tr>
<td>Amy</td>
<td>Aunty</td>
<td>02/19/1950</td>
<td>Master</td>
<td>Housewife</td></tr>
<tr>
<td>Eddie</td>
<td>Cousin</td>
<td>02/19/1990</td>
<td>Diploma</td>
<td>Editor</td>
</tr>
</tbody>
</table>
You can select each matched element using the :has selector. To match against minimum education you must build the selector string based on the array mapping the education strings to the $minimumEducation value
$( "tr:has(td[value="bachelor"], td[value="master"])" )
This can be generated similar to the following
var query = "";
for (var i = minimumEducation; i < eduarray.length; i++) {
query += ', td[value="'+eduarray[i]+'"]';
}
query = query.substring(1);
Then just put the query string inside the selector
$( "tr:has("+query+")" )

Categories

Resources