JS, which returns the first name:
$.ajax({
url: 'exm1.php',
type: 'get',
dataType: 'json',
success: function(data){
if( t<data.length){
for(var i=0;i<data.length;i++){
$("#output").html(data[i].fn);
}
}
},
error: function() {
// TODO: do error handling here
console.log('An error has occurred while fetching lat/lon.');
}
});
There are two things which I would like to sort out first:
It always overwrites the output div tag. I don't know how I can prevent this
setInterval should only run when there is a change in the database, or maybe when data.length changes, is there any way I could store the previous value of data.length and then compare with new data.length
If #output contains the first name, then you can target and save it into a variable on load
Example:
var firstname = $('#output').html();
And then all you have to do is compare the AJAX output with the variable.
Example:
if ( firstname != data )
$('#output').html(firstname);
To prevent overwriting your div tag, use the following.
$("#output").append(data[i].fn);
I don't understand what you mean by setinterval, please clarify in your code.
You can keep the html inside of the div by using this (vanilla javascript)
var inTheOutPutDiv = document.getElementById("output");
inputTheOutPutDiv.html = inputTheOutPutDiv.html + data; // whatever
// or use inputTheOutPutDiv.html+= data;
but sense you are using Jquery you can use append
$("#output").append(data);
You can instantiate a variable outside of your function that holds the length of your database query (scope). Or you can return a database value that says if the info has been updated (a value of 1 if changed, a value of 0 if the same). Then use a conditional statement to perform an action on the response. You have many options.
Unfortunately you can't call setInterval only when the data changes, but you can run something at a set interval and only update the #output html if the result is different.
The reason #output is getting overwritten is because calling $.html("...") will replace the existing html with the argument. I'd recommend simply putting what you want to remain static on the page in a different div.
<div id='oldOutput'>
Static Text Here: firstName?
<span id='output'></span>
</div>
Now your ajax return will overwrite the element and your static text will remain. However, you still have an issue in that every iteration of your loop will remove the string from before. If you want each loop to render cleanly, i'd recommend something along these lines:
success: function(data){
if( t<data.length){
// if you want to flush the #output each time
$("#output").html("");
for(var i=0;i<data.length;i++){
$("#output").append(data[i].fn);
// or you could put each entry in a div for later use
// $("#output").append("<div id='div_"+ i +"'>" + data[i].fn + "</div>");
}
}
}
In this case (you're flushing the div each time) then if the data is the same you shouldn't notice it update. If you don't flush the div then the data will keep appending on to the end.
If this is what you want, but only when there is new data, then you can count the number of child divs in the #output span - if you wrap each item from the output in a div as I have above, you should be able to compare this to data.length:
success: function(data){
if (t<data.length){
// gets direction descendants of #output that are divs,
// and counts the length of the array returned
var numItems = $("#output > div").length;
if(numItems != data.length){
loop goes here..
}
}
This will sort of work, it will only update when the number of items returned is different to the number of items you already have. However, if your script is returning a set of data and you need to filter it to see what's old and what's new, it's slightly different. You'll need to do include some sort of identifier (other than the data itself) to embed into the to check if it exists later.
if ( $("[data-id=" + data[i].identifier +"]").length > 0 ) {
// already exists, do nothing
} else {
$("#output").append("<div data-id='"+ data[i].identifier +"' etc...
}
Related
I'm trying to figure out a way to build a progress bar with React. I have a forEach loop that iterates through an array of about 7,000 indexes. Each time I validate a row, I want to update a state variable with percentage completion (and render this on the page live). I've tried iterating through these indexes, and updating my state variable (hoping to update the page) in the loop but I'm realizing that will not work. I obviously can't do this with a normal variable as it will reset when the component re-renders. Can anyone give me some insight on this topic?
Thanks.
Here is a code snippet from what I'm looking at:
parsedAssets.forEach(asset => {
newAssetValidated = validateBulkUpload(asset, parsedAssets, assetList, accountLogged, jobSites);
!newAssetValidated.reject_err ? validatedAssetList.accepted.push(newAssetValidated) : validatedAssetList.rejected.push(newAssetValidated);
setStateAssets({ ...stateAssets, validatedAssetList });
});
}
So essentially, as each asset is either accepted or rejected we add it to "stateAssets", and I'm hoping to build the progress bar from the length of the combined arrays that are getting set in stateAssets. However, when the forEach loop is completed, only the last validated asset is getting set due to it not updating until the forEach loop is completed.
Personally I can't imagine such a heavy validation, that you need progress-bar, but anyway.
First solution is to separate validation itself from state update for progress-bar into separate "threads". But since JS is single threaded, you may use some tricks with setTimeout or setInterval functionality. It may be very tricky, and in general not recommended practice with React.
Another way is - to set the work into queue & process 1 item at a time.
As an example I would do it something like this:
function ComponentWithProgress({parsedAssets, setParsedAssets}) {
const [validatedAssetList, setValidatedAssetList] = useState([])
const [progress, setProgress] = useState(0)
const [toDo, setToDo] = useState([])
if(parsedAssets && parsedAssets.length>0) {
setToDo(parsedAssets)
// clear parsedAssets in parent component to: [], false, null ...
// so you put it into toDo only once
setParsedAssets([])
}
if(toDo.length > 0) {
const asset = toDo[0]
const newToDo = toDo.slice(1) // All but 0th element
const newAssetValidated = validateBulkUpload(asset);
setValidatedAssetList([ ...validatedAssetList, newAssetValidated ]);
setToDo(newToDo)
setProgress( newToDo.length / ( validatedAssetList.length + newToDo.length ) * 100 )
}
// ... Render here
// If you need only accepted
const accepted = validatedAssetList.filter(v => !v.reject_err)
}
This example maybe not work for you as is, because you didn't showed us the context, but the main idea is here.
I have created an HTML web app in google script this works like a calculator, This app works fine if I add the input in descending order however if I skip the order and update in put data numbers randomly in any column then I am not getting the output properly
Example:- update the numbers in box number 4 and 5 then update in box number 1 you will find the differences in total numbers
Please refer the attached sheet for detailed script
Project Name- Project Proposal Form
$("#rTpe1").keyup(function(e){
$("#rFor1").val(this.value * $("#PerHourRate1").val());
$("#rFor3").val( Number($("#rFor1").val()) +Number($("#rFor2").val()))
});
$("#rTpe2").keyup(function(e){
$("#rFor2").val(this.value * $("#PerHourRate2").val());
$("#rFor3").val( Number($("#rFor1").val()) + Number($("#rFor2").val()))
});
$("#rTpe12").keyup(function(e){
$("#rFor12").val(this.value * $("#PerHourRate3").val());
$("#rFor3").val( Number($("#rFor1").val()) + Number($("#rFor2").val())+ Number($("#rFor12").val()))
});
$("#rTpe13").keyup(function(e){
$("#rFor13").val(this.value * $("#PerHourRate4").val());
$("#rFor3").val( Number($("#rFor1").val()) + Number($("#rFor2").val())+ Number($("#rFor12").val())+ Number($("#rFor13").val()))
});
I could be wrong, but I think that's the main culprit:
If your work your way top to bottom, the output in '#rFor3' is not affected. For example, if you enter values in the first field ('#rTpe1'), this statement
Number($("#rFor2").val()))
will evaluate to '0' because '#rFor2' probably contains an empty string at this point and Number("") will get you a zero. Because all subsequent input fields reference the results of previous calculations ('rTpe2' references 'rFor1', 'rTpe12' references both 'rFor1' and 'rFor2', etc), the sum will come out as correct.
Now consider the reverse scenario. For simplicity, let's make all your rates equal to 1. If you enter the value of '5' into 'rTpe12', the value of 'rFor3' will be
Number("") + Number("") + Number(5*1) == 5; //the first two inputs will contain empty strings at this point
The output of '#rFor3' would be 5. If you go up a step and enter the value of '2' into 'rTpe2', the value of the 'rFor3' output will change to
Number("") + Number(2*1) == 2; the first input will contain an empty string.
The code is not easy to understand, so even if this solution doesn't work for you, consider caching your DOM elements to improve performance and make your code more readable. Currently, you are using jQuery selectors to search the DOM over and over again, which is a serious performance drag. You could also store your calculated value as a variable and simply add values to it instead of recalculating on each input. For example
$('document').ready(function(){
var total = 0;
var input1 = $('#input1');
var input2 = $('#input1');
var input3 = $('#input1');
var output = $('#output');
input1.keyup(function(e){
var value = Number(this.value);
sum += value;
output.val(sum);
});
});
So I'm just getting to grips with node-red and I need to create a conditional global function.
I have two separate global.payloads set to a number value of either 0 or 1.
What I need to happen now is, if global.payload is equal to value 1 then follow this flow, if it is equal to value 0 then follow this one.
I'm just a little confused with the syntax for the function statement. Any help gratefully appreciated.
Since you haven't accepted the current answer, thought I'd give this a try.
I think this is what you need to handle inputs from two separate global contexts. I'm simulating them here with two separate inject nodes to demonstrate:
The checkconf inject node emits a 1 or a 0. Same for the meshstatus node. Substitute your real inputs for those inject nodes. The real work is done inside the function:
var c = context.get('c') || 0; // initialize variables
var m = context.get('m') || 0;
if (msg.topic == "checkconf") // update context based on topic of input
{
c = {payload: msg.payload};
context.set("c", c); // save last value in local context
}
if (msg.topic == 'meshstatus') // same here
{
m = {payload: msg.payload};
context.set('m', m); // save last value in local context
}
// now do the test to see if both inputs are triggered...
if (m.payload == 1) // check last value of meshstatus first
{
if (c.payload == 1) // now check last value of checkconf
return {topic:'value', payload: "YES"};
}
else
return {topic:'value', payload: "NO"};
Be sure to set the "topic" property of whatever you use as inputs so the if statements can discriminate between the two input. Good luck!
You can use the Switch node to do this, rather than a Function node.
I'm generating a table using xslt, but for this question I'll keep that side out of it, as it relates more to the actual generated structure of a html table.
What I do is make a vertical table as follows, which suits the layout needed for the data concerned that originated in a spreadsheet. Example is contrived for brevity, actual data fields contain lengthy strings and many more fields.
Title: something or rather bla bla
Description: very long desription
Field1: asdfasdfasdfsdfsd
Field2: asdfasfasdfasdfsdfjasdlfksdjaflk
Title: another title
Description: another description
Field1:
Field2: my previous field was blank but this one is not, anyways
etc.
The only way so far I found to generate such a html table is using repeating tags for every field and every record e.g.:
<tr><th>Title</th><td>something or rather bla bla</td></tr>
<tr><th>Description</th><td>very long desription</td></tr>
...
<tr><th>Title</th><td>another title</td></tr>
<tr><th>Description</th><td>another description</td></tr>
...
Of course this is semantically incorrect but produces correct visual layout. I need it to be semantically correct html, as that's the only sane way of later attaching a filtering javascript facility.
The following correct semantically produces an extremely wide table with a single set of field headers on the left:
<tr><th>Title</th><td>something or rather bla bla</td><td>another title</td></tr>
<tr><th>Description</th><td>very long desription</td><td>another description</td></tr>
...
So to summarise, need a html table (or other html structure) where it's one record under another (visually) with repeating field headers, but the field headers must not be repeated in actual code because that would wreck any record based filtering to be added later on.
Yo. Thanks for updating your question, and including some code. Typically you'd also post what you've tried to correct this issue - but I'm satisfied enough with this post.
Since you want the repeating headers in vertical layout (not something I've seen often, but I can understand the desire), you don't have to modify the HTML formatting, just use a bit more JavaScript to figure it out. I haven't gone through and checked to see if I'm doing things efficiently (I'm probably not, since there are so many loops), but in my testing the following can attach to a vertical table and filter using a couple variables to indicate how many rows there are in each entry.
Firstly, here's the HTML I'm testing this one with. Notice I have a div with the id of filters, and each of my filter inputs has a custom attribute named filter that matches the header of the rows they are supposed to filter:
<div id='filters'>
Title: <input filter='Title'><br>
Desc: <input filter='Description'>
</div>
<table>
<tr><th>Title</th><td>abcd</td></tr>
<tr><th>Description</th><td>efgh</td></tr>
<tr><th>Title</th><td>ijkl</td></tr>
<tr><th>Description</th><td>mnop</td></tr>
<tr><th>Title</th><td>ijkl</td></tr>
<tr><th>Description</th><td>mdep</td></tr>
<tr><th>Title</th><td>ijkl</td></tr>
<tr><th>Description</th><td>mnop</td></tr>
<tr><th>Title</th><td>ijkl</td></tr>
<tr><th>Description</th><td>mnop</td></tr>
</table>
Here are the variables I use at the start:
var filterTable = $('table');
var rowsPerEntry = 2;
var totalEntries = filterTable.find('tbody tr').size() / rowsPerEntry;
var currentEntryNumber = 1;
var currentRowInEntry = 0;
And this little loop will add a class for each entry (based on the rowsPerEntry as seen above) to group the rows together (this way all rows for an entry can be selected together with a class selector in jQuery):
filterTable.find('tbody tr').each(function(){
$(this).addClass('entry' + currentEntryNumber);
currentRowInEntry += 1;
if(currentRowInEntry == rowsPerEntry){
currentRowInEntry = 0;
currentEntryNumber += 1;
}
});
And the magic; on keyup for the filters run a loop through the total number of entries, then a nested loop through the filters to determine if that entry does not match either filter's input. If either field for the entry does not match the corresponding filter value, then we add the entry number to our hide array and move along. Once we've determined which entries should be hidden, we can show all of the entries, and hide the specific ones that should be hidden:
$('#filters input').keyup(function(){
var hide = [];
for(var i = 0; i < totalEntries; i++){
var entryNumber = i + 1;
if($.inArray(entryNumber, hide) == -1){
$('#filters input').each(function(){
var val = $(this).val().toLowerCase();
var fHeader = $(this).attr('filter');
var fRow = $('.entry' + entryNumber + ' th:contains(' + fHeader + ')').closest('tr');
if(fRow.find('td').text().toLowerCase().indexOf(val) == -1){
hide.push(entryNumber);
return false;
}
});
}
}
filterTable.find('tbody tr').show();
$.each(hide, function(k, v){
filterTable.find('.entry' + v).hide();
});
});
It's no masterpiece, but I hope it'll get you started down the right path.
Here's a fiddle too: https://jsfiddle.net/bzjyfejc/
I have four CSVs with the same header information, each representing a quarterly result within a year.
Therefore for one result I can load it and display it into a dataTable simple via
d3.csv("data/first-quarter"), function(dataQ1){
dataQ1.forEach(function(d){
d.callTypes = d['Call Types'];
d.callDesc = d['Call Description'];
d.callVol = d['Call Volume'];
d.quarter = 'Q1';
});
var facts = crossfilter(dataQ1);
var timeDimension = facts.dimension(function(d){
return d.quarter;
});
dataTable
... //data table attributes
dc.renderAll();
});
However complications arise when I try to retrieve from multiple sources and append the results.
One approach I took was to place all the file path names into an array and iterate through a forEach, with a flag to show when it was the last iteration to render the table. But this failed with a "Too many recursion" error.
And the next was to nest as such
d3.csv(filesPathNames[0], function(dataQ1){
d3.csv(filesPathNames[1], function(dataQ2){
d3.csv(filesPathNames[2], function(dataQ3){
d3.csv(filesPathNames[3], function(dataQ4){
But both of these methods seem to not work due to the fact that I can't simply add one CSV value to another. So I think where I'm having an issue is that I'm not sure how to concatenate dataQ1, dataQ2, dataQ3, and dataQ4 properly.
Is the only solution to manually append one to another with an added value of Q1, Q2, Q3, and Q4 as the time dimension?
Like Lars said, you can use the queue library. Here is an example of how this might work:
Step 1) Queue up your files:
<script type="text/javascript" src="http://d3js.org/queue.v1.min.js"></script>
var q = queue()
.defer(d3.csv, "data/first-quarter")
.defer(d3.csv, "data/second-quarter");
Step 2) Wait for the files to load:
q.await(function(error, q1data, q2data) {
Step 3) Add the data to crossfilter:
var ndx = crossfilter();
ndx.add(q1data.map(function(d) {
return { callTypes: d['Call Types'],
callDesc: d['Call Description'],
callVol: d['Call Volume'],
quarter: 'Q1'};
}));
ndx.add(q2data.map(function(d) {
return { callTypes: d['Call Types'],
callDesc: d['Call Description'],
callVol: d['Call Volume'],
quarter: 'Q2'};
}));
Step 4) Use your cross filter as you wish:
var timeDimension = ndx.dimension(function(d){
return d.quarter;
});
dataTable
... //data table attributes
dc.renderAll();
Here is an example using this approach with the dc.js library: https://github.com/dc-js/dc.js/blob/master/web/examples/composite.html