Accessing specific data from csv file and show on html - javascript

Having some problems accessing specific data from a csv file. Currently I can see all data in the console but when I try to show a specific data getting undefined. For example in my console I get all data and I want to extract the subtitles and show it on the html in a class score-text.
My console looks like this:
subtitle 1,
name1,65%
name2,65%
name3,65%
name4,65%
total,70%
,
subtitle 2,
name1,65%
name2,65%
name3,65%
name4,65%
total,30%
,
subtitle 3,
name1,65%
name2,65%
name3,65%
name4,65%
total,60%
,
subtitle 4,
name1,65%
name2,65%
name3,65%
name4,65%
total,50%
$.ajax({
url: 'test.csv',
type: "GET",
dataType: "text",
success: function (data) {
var rows = data.split(/\n/);
for (var rowIndex in rows)
{
var columns = rows[rowIndex].split(/,/);
for (var colIndex in columns)
{
var colValue = columns[colIndex].trim();
console.log(colValue);
}
}
$(".score-text").each(function( index, value ) {
value.innerHTML = result[columns[2]] = rows[2];
});
}
});

Why don't you try putting the insertion part into the loop?
var columns = rows[rowIndex].split(/,/);
for (var colIndex in columns)
{
var colValue = columns[colIndex].trim();
console.log(colValue);
$(".score-text").append(colValue);
}

Related

How to set json data into a html table

i want to display these json data into a html table. i am trying to do many things but i cant figure out how can i do it. So anyone can please help me to fix it.
the json data set will appear in the console. but i cant set it to a table.
this is my model
public function displayRecords()
{
$this->db->select('A.*');
$this->db->from('rahu AS A');
$this->db->where('A.status',1);
return $this->db->get()->result_array();
}
this is my controller
public function allrecodes()
{
/*script allow*/
if (!$this->input->is_ajax_request()) {
exit('No direct script access allowed here.');
}
$response= array();
$response['result'] = $this->RahuModel->displayRecords();
echo json_encode($response);
}
this is my js
var get_rec = function(){
//alert("WWW");
$.ajax({
//request ajax
url : "../dashbord/allrecodes",
type : "post",
contentType: "application/json",
dataType : "json",
success: function(dataset) {
//var myobject = JSON.stringify(result);
//alert(myobject[0]);
console.log(dataset);
console.log(dataset.result[0]['id']);
},
error: function() { alert("Invalide!"); }
});
};
the json dataset will appear in console.
And also this get_rec() in js file will called top of the page.
$(document).ready(function() {
//alert("Hello, world!");
get_rec();});
can anyone please help me to fix it.. thank you !!
There is no "simple" way to do it. You will have to loop through the resultset and render the html.
function renderTable(data) {
var result = ['<table>'];
var header = false;
for (var index in data) {
var row = data[index];
if (!header) {
// Create header row.
header = Object.keys(row);
var res = ['<tr>'];
for (var r in header) {
res.push("<th>" + header[r] + "</th>");
}
res.push('</tr>');
result.push(res.join("\n"));
}
// Add data row.
var res = ['<tr>'];
for (var r in header) {
res.push("<td>" + row[header[r]] + "</td>");
}
res.push('</tr>');
result.push(res.join("\n"));
}
result.push('</table>');
return result.join("\n");
}
document.getElementById('output').innerHTML = renderTable(data);
Have a div tag with id output on your HTML
<div id="output"></div>

How to make datatable specific column editable?

There are various questions put up on this topic but I do not understand them so can anyone help
here is my js code
$(document).ready(function () {
$('#myModal').toggle();
var List = [];
$.ajax({
url: '/urls/' + id,
type: 'POST',
dataType: "json",
data: 'data',
success: function (data) {
console.log("data length: ", data.length);
console.log("data : ", data);
for (var i = 0; i < data.length; i++) {
var Logs = {};
Logs.Info = data[i].Info;
for (var j = 0; j < Logs.Info.length; j++) {
var emplist = {};
emplist.Name = Logs.Info[j].Name;
emplist.dates = Logs.Info[j].dates;
for (var k = 0; k < emplist.dates.length; k++) {
var datelist = {};
datelist.Name = emplist.Name;
datelist.startDate = emplist.dates[k].startDate;
datelist.endDate = emplist.dates[k].endDate;
List.push(datelist);
}
}
}
emptablee = $('#Table').DataTable({
"data": List,
"columns": [
{"data": "Name"},
{"data": "startDate"},
{"data": "endDate"},
],
destroy: true,
"scrollY": "200px",
"scrollCollapse": true,
"paging": false
});
/*emptablee.destroy();*/
}
});
$("#close").on('click', function () {
$("#myModal").hide();
});
});
There are three columns in the table and I want to make a specific columns cell-like editable and show an input box and get the value edited to send.
For anyone checking this now, I've created a custom example in which you can make any column editable by just sending it in a metadata request from serverside.
here : https://github.com/sinhashubh/datatable-examples
If you want, for example, your startDate column to be editable, you need to init the Datatables like this so you can hit the column by class name:
{"data": "startDate", "className": "editable"},
then, with proper event handling
// Activate an inline edit on click of a table cell
$('#Table').on( 'click', 'tbody td.editable', function (e) {
editor.inline( this );
} );
and initializing Editor you will be good:
editor = new $.fn.dataTable.Editor( {
ajax: "../ajax/handle-data.php", // path to back-end data handling
table: "#Table",
fields: [ {
label: "Start Date:",
name: "startDate"
}
]
} );
Also, don't forget to add this outside of document ready handler because you need it as a global var:
var editor;
Full example here (note that Datatables Editor feature is not free) https://editor.datatables.net/examples/inline-editing/columns.html
You can also code up your own completely free version, which is slightly more complicated, without using Editor, but still using class names so you can trigger on click events for specific columns.

Replace javascript variable without id or class

I have this javascript and once the AJAX process is executed I want to replace this variable to some other variable.
window.onload = function() {
oldvariable = [];
var chart = new Chart("Container2", {
data: [{
type: "column",
dataPoints: oldvariable
}]
});
}
When I process the AJAX request and fetch JSON data which is stored in oldvariable, it is not written so I have few options. I tried ads they are working in HTML but not under script tag.
If I can define oldvariable='<div class="second"></div>'; and replace this with processed JSON data then it is working and giving correct output in HTML but in javascript < tag is not allowed as variable so we cant define oldvariable like that.
$( "div.second" ).replaceWith( ''+newvariable +'' );
So is there anyway I can replace javascript variable as HTML tags are not allowed in variable and without tag javascript can't replace.
I have one more probable solution.regex. Search for oldvariable in entire HTML code and replace with newvariable but that process will be very slow so what is the best way to do this.
My vairables are globally defined and AJAX request is in external file and above codes are embeded in HTML.
========edit
how we can replace oldvariable with newvariable in above javascript
====== ajax code- variable name is different
$(document).ready(function() {
(function() {
$('#upload-form2').ajaxForm({
dataType: 'json',
success: function(data) {
var oldvariable = '',
downlo;
for (var i = 0; i < data.length; i++) {
downlo = data[i];
oldvariable += '' + downlo.ndchart + '';
}
$('#chek').html(oldvariable );
}
})
})();
});
you need to update chart datapoints and re-render the chart after ajax success like this
ajax :
...
success:function(response)
{
chart.options.data[0].dataPoints=response;
//response is (array) of dataSeries
chart.render();
}
.......
update 1 : As per your code data should be updated like this
.....
success:function(data) {
var new_data = [];
for (var i = 0; i < data.length; i++)
{
new_data.push({y:data[i].ndchart });
}
chart.options.data[0].dataPoints=new_data;
chart.render();
}
.....
update 2:
$(document).ready(function() {
(function() {
$('#upload-form2').ajaxForm({
dataType: 'json',
success: function(data) {
var new_data = [];
for (var i = 0; i < data.length; i++)
{
new_data.push({y:data[i].ndchart });
}
chart.options.data[0].dataPoints=new_data;
chart.render();
}
})
})();
});

Displaying php result in HTML using AJAX

I am trying to display the result of my php in different <div>-s. My plan is that I make a query in my php and display the result in JSON format. Due to the JSON format my result can be displaying in different <div>. How can I reach that for example the "name" can be displayed between <div> tags?
The example result of php:
[
{
"id": 0,
"name": "example1",
"title": "example2"
},
{
"id": 0,
"name": "example1",
"title": "example2"
}
]
The attempt:
<div class="result"></div>
<script>
$.ajax({
type:'GET',
url:'foo.php',
data:'json',
success: function(data){
$('.result').html(data);
}
});
</script>
Hi try parsing the returned data into a JSON object :
<div class="result"></div>
<script>
$.ajax({
type:'GET',
url:'foo.php',
data:'json',
success: function(data){
// added JSON parse
var jsonData = JSON.parse(data);
// iterate through every object
$.each(jsonData, function(index, element) {
// do what you want with each JSON object
$('.result').append('<div>' + element.name + '</div>');
});
}
});
</script>
// PS code is untested.
// Regards
Do it like below:-
success: function(data){
var newhtml = ''; //newly created string variable
$.each(data, function(i, item) {//iterate over json data
newhtml +='<div>'+ item.name +'</div>'; // get name and wrapped inside div and append it to newly created string variable
});
$('.result').html(newhtml); // put value of newly created div into result element
}
You can create it like this:
for (var i = 0; i < res.length; i++) {
var id = $("<div></div>").html(data[i].id);
var name = $("<div></div>").html(data[i].name);
var title = $("<div></div>").html(data[i].title);
$('.result').append(id).append(name).append(title);
}

Display only most recent row of data in Google Sheet from api call

I'm trying to print the most recent row from a Google Sheet, which updates daily. I'm making an API call to it and returning it in Json and whilst I can grab the most recent value, I can only seem to print the whole column of data:
I apologise the code is a bit slap and dash, I'm new to this.
Javascript
var sheetsuUrl = "https://sheetsu.com/apis/v1.0/3e242af0";
$.ajax({
url: sheetsuUrl,
dataType: 'json',
type: 'GET',
// place for handling successful response
success: function(data) {
console.log(data[data.length-1]['moved'])
addCharacters(data);
},
// handling error response
error: function(data) {
console.log(data);
}
});
addCharacters = function(characters) {
var list = $('#ponies');
for(var i=0; i<characters.length; i+=1) {
char = characters[i];
function lastNoZero(myRange) {
lastRow = myRange.length;
for (; myRange[lastRow - 1] == "" || myRange[lastRow - 1] == 0 && lastRow > 0 ; lastRow--) {
/*nothing to do*/
}
return myRange[lastRow - 1];
}
myRange = char.moved;
if (char.moved == 'entered') {
html = "<img src='https://media.firebox.com/pic/p5294_column_grid_12.jpg'/>";
} else {
html = "<img src='http://41.media.tumblr.com/30b1b0d0a42bca3759610242a1ff0348/tumblr_nnjxy1GQAA1tpo3v2o1_540.jpg'/>";
};
list.append(html);
}
}
HTML
<script src="https://code.jquery.com/jquery-3.0.0-alpha1.js"></script>
<div id="ponies"></div>
CSS
html img{
width:100px;
height:100px;
}
You needed to reference the last item in the array returned by your GET request.
characters[characters.length - 1]; will get the last character in the characters array. Then, to ensure that the html is not added on each run of the loop, you needed to move list.append(html); outside the loop, ensuring that it only appends the content to the page once.
Run the code snippet below to see in action.
var sheetsuUrl = "https://sheetsu.com/apis/v1.0/3e242af0";
$.ajax({
url: sheetsuUrl,
dataType: 'json',
type: 'GET',
// place for handling successful response
success: function(data) {
addCharacters(data);
},
// handling error response
error: function(data) {
console.log(data);
}
});
addCharacters = function(characters) {
var list = $('#ponies');
for(var i=0; i<characters.length; i+=1) {
char = characters[characters.length - 1];
myRange = char.moved;
if (char.moved == 'entered') {
html = "<img src='https://media.firebox.com/pic/p5294_column_grid_12.jpg'/>";
} else {
html = "<img src='http://41.media.tumblr.com/30b1b0d0a42bca3759610242a1ff0348/tumblr_nnjxy1GQAA1tpo3v2o1_540.jpg'/>";
};
}
//for illustration purposes
list.append(characters[characters.length - 1].time)
//the code to attach the image
list.append(html);
}
<script src="https://code.jquery.com/jquery-3.0.0-alpha1.js"></script>
<div id="ponies"></div>

Categories

Resources