how to extract data from a csv to javascript - javascript

I am trying to extract data from a CSV with JavaScript and then put these values into an array and display it. My csv will have multiple rows (5 or more). So far i am trying to use a jquery library to help extract the data. I couldn't get the script to display anything when I ran it. I am new to Javascript so wasn't sure how to do this and how to take the extracted data and put it into an array.
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title> Testing Orders</title>
</head> <body>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "GET",
url: "tester excel.csv",
dataType: "text",
success: function(data) {processData(data);}
});
});
function processData(allText) {
var allTextLines = allText.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
var lines = [];
for (var i=1; i<allTextLines.length; i++) {
var data = allTextLines[i].split(',');
if (data.length === headers.length) {
var tarr = [];
for (var j=0; j<headers.length; j++) {
tarr.push(headers[j]+":"+data[j]);
}
lines.push(tarr);
}
}
// alert(lines);
// console.log("tester excel.txt");
}
function getData() {
if (data == ""){
return 'DataNotReady';
}else {
}
}
windows.prompt(processData);
</script>
</body>
</html>`

Related

Pass javascript array to C# code Razor pages

I have the following JavaScript code in Index.cshtml
function getActivity()
{
var collection = document.getElementsByClassName("skill-icon-selected");
const splitCollection = new Array;
for (var i = 0; i < collection.length; i++)
{
var split = collection[i].id.split("-");
splitCollection.push(split[0]);
}
console.log(splitCollection);
}
I want to pass the array splitCollection to Index.cshtml.cs to use
public List<Activity> allActivities = new List<Activity>();
public void OnGet()
{
allActivities = _context.Activities.ToList();
foreach (var activity in allActivities)
{
if (splitCollection.contains(activity.Skill))
{
//Do stuff
}
}
How would I access splitCollection in my cshtml.cs or the data in splitCollection to be usesd in c#
Since you want to pass an array to cshtml.cs in razor page,you need to use Post method.So you can pass data to OnPost handler,here is a demo:
cshtml:
#Html.AntiForgeryToken()
#section Scripts{
<script>
function getActivity() {
var collection = document.getElementsByClassName("skill-icon-selected");
const splitCollection = new Array;
for (var i = 0; i < collection.length; i++)
{
var split = collection[i].id.split("-");
splitCollection.push(split[0]);
}
console.log(splitCollection);
$.ajax({
type: "POST",
url: "",
data: JSON.stringify(splitCollection),
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
contentType: "application/json",
success: function (data) {
}
});
console.log(splitCollection);
}
</script>
}
cshtml.cs:
public void OnPost([FromBody] List<Activity> myAllActivities)
{
...
}

Use PHP file in Javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have a PHP file contain some calculation. Now, I want to integrate the calculation into javascript in another file. How i can pass the variable in javascript to do calculation inside php?
this is my javascript code:
$("#upload").on("click", function(){
var csv = $('#csv');
var csvFile = csv[0].files[0];
var ext = csv.val().split(".").pop().toLowerCase();
if($.inArray(ext, ["csv"]) === -1){
alert('upload csv');
return false;
}
if(csvFile != undefined){
reader = new FileReader();
reader.onload = function(e){
csvResult = e.target.result.split(/\r|\n|\r\n/);
var temp=[];
for(i=0;i< csvResult.length; i++){
if(csvResult[i] != "" && csvResult[i] != null){
var data = csvResult[i].split(",");
var rssi = data[0];
var distance = data[1];
var rssisample = 8;
if(distance == 1){
//need to insert calculation method from php
temp.push(rssi);
}
}
}
I have php file name myphpfile.php. So, I want to use variable and value from javascript to perform calculation in php file and return back to javascript. Please help me on this
This is my some part of php file. eg: myphpfile.php
<?php
// $arrTimeRSSI will read from javascript before perform this calculation
//calculate mean X using array_sum() method
$avgRSSI = array_sum($arrTimeRSSI)/($num_of_elements);
function StandardDeviation($arrTimeRSSI){
global $num_of_elements;
global $avgRSSI;
$variance = 0.0;
foreach($arrTimeRSSI as $x){
//sum of squares of difference between all numbers and mean X
$variance += pow(($x - $avgRSSI), 2);
}
$newElements = $num_of_elements - 1;
return (float)sqrt($variance/$newElements);
} ?>
It is not that simple because PHP is executed on the server and JavaScript by the client. You have to use ajax to send your request with data to a php script (to the server) and get the response back to the client.
This is an example how your JavaScript can look like:
$("#upload").on("click", function(){
var csv = $('#csv');
var csvFile = csv[0].files[0];
var ext = csv.val().split(".").pop().toLowerCase();
if($.inArray(ext, ["csv"]) === -1){
alert('upload csv');
return false;
}
if(csvFile != undefined){
reader = new FileReader();
reader.onload = function(e){
csvResult = e.target.result.split(/\r|\n|\r\n/);
var temp=[];
for(i=0;i< csvResult.length; i++){
if(csvResult[i] != "" && csvResult[i] != null){
var data = csvResult[i].split(",");
var rssi = data[0];
var distance = data[1];
var rssisample = 8;
if(distance == 1){
$.ajax({
url: '/path/to/phpfile.php',
type: 'post',
// transmit your data
data: {number1: '15', number2: '15'},
success: function (response) {
// handle the response
// response should contain 225 in this example
}
});
temp.push(rssi);
}
}
}
}
}
});
And this is how your PHP file at /path/to/phpfile.php could look like:
// do your calculations here and echo it
echo intval($_POST['number1']) * intval($_POST['number2']);
Another method is to make a php file and embed your javascript in it.
But this solution does not allow you to transfer data from javascript to php. Because the php function is executed on the server and the javascript (with the calculated part) is send to the client after that. Like this example:
<?php
// declare your php function here
function calculate() {
return;
}
?>
<script>
$("#upload").on("click", function(){
var csv = $('#csv');
var csvFile = csv[0].files[0];
var ext = csv.val().split(".").pop().toLowerCase();
if($.inArray(ext, ["csv"]) === -1){
alert('upload csv');
return false;
}
if(csvFile != undefined){
reader = new FileReader();
reader.onload = function(e){
csvResult = e.target.result.split(/\r|\n|\r\n/);
var temp=[];
for(i=0;i< csvResult.length; i++){
if(csvResult[i] != "" && csvResult[i] != null){
var data = csvResult[i].split(",");
var rssi = data[0];
var distance = data[1];
var rssisample = 8;
if(distance == 1){
var calculation = <?php echo calculate(); ?>
temp.push(rssi);
}
}
}
}
}
});
</script>
this can be done by creating a formdata and pass it to the php file which on it returns values.
In my experience it is best to pass json values and return them from the php file as well.
javascript function:
function example(){
var form_data = new FormData();
form_data.append("Variable1ToPass","test1");
form_data.append("Variable2ToPass","test2");
$.ajax({
url: '/ThePhpFileYourReferTo.php',
type: 'POST',
dataType: 'json',
cache: false,
async: false,
data: form_data,
contentType: false,
processData: false,
error: function(ReturnData){
//here do the error handling
console.log(ReturnData);
return;
},
success: function(ReturnData) {
console.log(ReturnData.ResultOfCalculation);
return;
}
});
}
In the php file (ThePhpFileYourReferTo.php):
$DataToReturn = [];
$DataToReturn['SubmittedValue'] = $_POST;
$Variable2ToPass = $_POST['Variable2ToPass'];
$Variable2ToPass = $_POST['Variable2ToPass'];
//here do the calculation and write in the return variable
$DataToReturn['ResultOfCalculation'] = "OK DONE";
header('Content-type: application/json');
echo json_encode($DataToReturn);

Progress Bar in ajax while uploading 2 files or more

Hi Im trying to upload a 2 file or more, my problem is my progress bar will say 100% because of the small file being uploaded first, then its going back to the percent of the large file.. My question is how can I have a same progress if i have many files being uploaded?
$('body').on('change', 'input:file.gallery_images', function(event)
{
event.preventDefault();
var data = new FormData();
data.append('id', $("#id").val());
var count = $(this)[0].files.length;
$.each($(this)[0].files, function(i, file)
{
data.append('userfile', file);
$.ajax(
{
type: "POST",
url: href+path+"/imagens/store",
data: data,
mimeType: 'multipart/form-data',
contentType: false,
cache: false,
processData: false,
dataType: "json",
xhr: function()
{
var _xhr = $.ajaxSettings.xhr();
_xhr.addEventListener('progress', function (event) { }, false);
if (_xhr.upload)
{
_xhr.upload.onprogress = function(event)
{
var percent = 0;
if (event.lengthComputable)
{
var position = event.position || event.loaded;
var total = event.totalSize || event.total;
percent = Math.ceil(position / total * 100);
}
$("#progress-bar").width(percent + '%');
};
}
return _xhr;
},
beforeSend: function()
{
$("#progress").fadeIn('slow');
$("#progress-bar").width('0%');
},
success: function(data)
{
if(data.gallery)
{
if($(".alert").length > 0)
{
$(".alert").hide('slow').remove();
$("#droppable").show('slow');
}
$('.gallery').fadeTo('300', '0.5', function () {
$(this).html($(this).html() + data.gallery).fadeTo('300', '1');
});
}
$("#progress").fadeOut('slow');
}
});
});
});
Ok, first thing I noticed is that you're adding the file to the 'data' variable inside your $.each... but that means the first POST contains the first image, the second POST contains the first and the second, and so on. I think you should this part inside your $.each:
var data = new FormData();
data.append('id', $("#id").val());
Ok, so, to solve your problem: Before sending anything, go through them and sum their size. You'll also need to store the progress for each file individually, so start it as zero:
var sumTotal = 0;
var loaded = [];
for (var i = 0, list = $(this)[0].files; i < list.length; i++) {
sumTotal += list[i].size;
loaded[i] = 0;
}
Inside your onprogress, instead of comparing the event.position with the event.totalSize, you'll store this position on your 'loaded' array, sum all your array, and then compare it to your sumTotal.
loaded[i] = event.position || event.loaded;
var sumLoaded = 0;
for (var j = 0; j < loaded.length; j++) sumLoaded += loaded[j];
percent = Math.ceil(sumLoaded * 100/sumTotal);
;)

Chart.js with JSON empty

I'm having problems using readings from my json file to fill in the chart. I found a function from here that allows me to pass the api url and returns the JSON data and that works, I then decided to loop through the JSON array adding each reading in an array and then passing that array into the chart function but when I load the page the chart is empty, here is the code `
<!DOCTYPE html>
<html lang="en">
<head>
<script src="Chart.js"></script>
</head>
<body>
<canvas id="myChart" width="400" height="400"></canvas>
<div id="result"></div>
<script>
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
var json = getJSON('http://ec2-54-152-138-146.compute-1.amazonaws.com:9000/system/listSystems').then(function(data) {
alert(data.data[0].waterLevel);
var chartData =[];
for (var i = 0; i < data.length; i++){
chartData.push(data.data[i].waterLevel);
}
alert(chartData);
var barData = {
labels: ['Italy', 'UK', 'USA', 'Germany', 'France', 'Japan'],
datasets: [
{
label: '2010 customers #',
fillColor: '#382765',
data: chartData
},
{
label: '2014 customers #',
fillColor: '#7BC225',
data: chartData
}
]
};
var context = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(context).Bar(barData)
result.innerText = data.data; //display the result in an HTML element
},
function(status) { //error detection....
alert('Something went wrong.');
});</script>
</body>
</html>
Your loop is incorrect, look at the stop condition in the for cycle.
You have to use data.data.length instead of data.length:
For reference:
for (var i = 0; i < data.data.length; i++)
Change
for (var i = 0; i < data.length; i++)
to
for (var i = 0; i < data.data.length; i++)

Difficulty in loading multiple images in a list view served by multiple xml files

I am developing a html application for Android and I am trying to load images in a list view. Data specific to list items is being served by multiple xml files. I am using ajax to load xml files and populate the list items. Problem I am facing here is that there are 164 list items. Hence, 164 images and 10 xml files to load. my loader function exhausts after two iterations. It does read the xml files but it's unable to dynamically create list items and populate them with images after two iterations. I believe it's due to stack limitations. I can't think of alternate solution. If somebody could suggest an alternate solution that will be highly appreciated. Below is my loader function. It's a recursive function:
function loadChannels() {
$.ajax({
type: "GET",
url: curURL,
dataType: "xml",
error: function(){ console.log('Error Loading Channel XML'); },
success: function(nXml) {
var noOfItems = parseInt($($(nXml).find('total_items')[0]).text(), 10);
var startIdx = parseInt($($(nXml).find('item_startidx')[0]).text(), 10);
var allItems = $(nXml).find('item');
$(allItems).each(function() {
var obj = $("<li><span id='cont-thumb'></span><span id='cont-name'></span></li>");
$("#content-scroller ul").append($(obj));
var imgURL = $($(this).find('item_image')[0]).text();
var contThumb = $(obj).children()[0];
$(contThumb).css("background-image", 'url('+imgURL+')');
var name = $($(this).find('name')[0]).text();
var contName = $(obj).children()[1];
$(contName).text(name).css('text-align', 'center');
var url = $($(this).find('link')[0]).text();
$(obj).data('item_link', url);
$(obj).bind('click', onJPContSelected);
});
if(startIdx+allItems.length < noOfItems){
var newIdx = new Number(startIdx+allItems.length);
var tokens = curURL.split("/");
tokens[tokens.length-2] = newIdx.toString(10);
curURL = "http:/";
for(var i=2; i<tokens.length; i++)
curURL = curURL + "/" + tokens[i];
loadChannels();
}
}
});
}
try to remove the recursion with an outer loop - something like that:
function loadChannels(){
var stopFlag = false;
// request the pages one after another till done
while(!stopFlag)
{
$.ajax({
type: "GET",
url: curURL,
dataType: "xml",
error: function(){
console.log('Error Loading Channel XML');
errorFlaf = true;
},
success: function(nXml) {
var noOfItems = parseInt($($(nXml).find('total_items')[0]).text(), 10);
var startIdx = parseInt($($(nXml).find('item_startidx')[0]).text(), 10);
var allItems = $(nXml).find('item');
$(allItems).each(function() {
var obj = $("<li><span id='cont-thumb'></span><span id='cont-name'></span></li>");
$("#content-scroller ul").append($(obj));
var imgURL = $($(this).find('item_image')[0]).text();
var contThumb = $(obj).children()[0];
$(contThumb).css("background-image", 'url('+imgURL+')');
var name = $($(this).find('name')[0]).text();
var contName = $(obj).children()[1];
$(contName).text(name).css('text-align', 'center');
var url = $($(this).find('link')[0]).text();
$(obj).data('item_link', url);
$(obj).bind('click', onJPContSelected);
});
if(startIdx+allItems.length < noOfItems){
var newIdx = new Number(startIdx+allItems.length);
var tokens = curURL.split("/");
tokens[tokens.length-2] = newIdx.toString(10);
curURL = "http:/";
for(var i=2; i<tokens.length; i++)
curURL = curURL + "/" + tokens[i];
// lets disable the recursion
// loadChannels();
}
else {
stopFlag = true;
}
}
});
}
}

Categories