Empty table body in jQuery DataTables - javascript

I'm a newbie to jQuery, so, please, don't judge me for my dumb question.
What I'm trying to achieve is fill datatable with exchange rates, sourced by API.
So, I managed to construct datatable, but its body is empty and there're no errors in the console, it's just "loading..." message where my data is supposed to be.
Searching for similar topics just didn't get any results. I would be thankful for your help, because I'm banging my head against that wall for 2 days already.
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<table id="rates"></table>
</body>
var key = '8366e7a49e014c729111a0ac6e5c7d9d';
var url = 'https://openexchangerates.org/api/latest.json?app_id=';
var dataTable = $('#rates').DataTable({
sDom: 't',
ajax: {
url: url + key
},
columns: [{
title: 'currency'
},{
title: 'rate'
}]
});

Seems like your data is structured improperly. Each data entry must correspond to DataTables row, so your code should be something like:
var key = '8366e7a49e014c729111a0ac6e5c7d9d';
var url = 'https://openexchangerates.org/api/latest.json?app_id=';
var dataTable = $('#rates').DataTable({
sDom: 't',
ajax: {
url: url+key,
dataSrc: function(data){
let apiData = [];
$.each(data.rates, function(index, entry){
apiData.push({currency:index, rate:entry});
});
return apiData.slice(0,10);
}
},
columns: [
{title:'currency', data:'currency'},
{title:'rate', data:'rate'}
]
});
<!doctype html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<table id="rates"></table>
</body>
</html>

Related

Search for word and color it

I am trying to search for a word in iframe and color it using angularjs and jquery. For jquery code i took help from #andrew stackoverflow.
In Jquery code if condition is there, controller is not going inside if condition. please help me to solve the problem.
Here is my complete code, which contains angular code and jquery code.
Angular code is working just fine, in the console i am able to see all the consoles, first i am parsing the arrays and taking out only the string required to search in the jquery. After that i am using that search word to search in the the iframe. But i am facing some problem with the jquery code.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html ng-app="app">
<head>
<title>
<%=t itle %>
</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="http://fonts.googleapis.com/css?family=Lato" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
</head>
<body>
<div ng-controller="ToddlerCtrl">
<h2>Sample</h2>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular-animate.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-resource.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script type="text/javascript" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.13.3.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<iframe src="text.txt" id="myIframe"></iframe>
<script type="text/javascript">
var myApp = angular.module('app', []);
myApp.controller('ToddlerCtrl', function($scope) {
// Define an array of Toddler objects
$scope.toddlers = [
[100, ["sample"]],
[100, ["used"]],
[100, ["tag"]],
[33.33333333333334, ["file"]]
];
for (var key in $scope.toddlers) {
if ($scope.toddlers.hasOwnProperty(key)) {
var temp = JSON.stringify($scope.toddlers[key][1])
var final_string = temp.slice(2, -2);
var searchWord = final_string;
// console.log(searchWord)
$(document).ready(function() {
$('#myIframe').ready(function() {
var $html = $($('#myIframe').contents().find('body').html());
if ($html.contents().text().search(searchWord) != -1) {
// Some problem with the if condition i guess.
// Controller is not entering if condition.
var replaceWith = "<span style='color:red'>" + searchWord + "</span>"
var newHTML = $html.text().replace(searchWord, replaceWith);
$('#myIframe').contents().find('body').html(newHTML);
}
});
});
// alert($scope.toddlers[key][1]);
// console.log("searchWord")
}
}
});
You can do it easily with Jquery, you can use this function on Javascript:
function findAndColorWord(html, word, color){
var indexWordStart = html.indexOf(word);
var wordLength = word.length;
var coloredWord = '<span style="color: '+color+'">'+word+'</span>';
var firstHtmlPart = html.substring(0, indexWordStart - 1);
var secondHtmlPart = html.substring(indexWordStart + wordLength, html.length - 1);
return firstHtmlPart + coloredWord + secondHtmlPart;
}
You only need to get the position of the word in the html of the iframe, that you can get with $("#id-of the iframe")[0].outerHTML , and after insert in that position a span element with the colored style for the word.
I maked a basic example with a Div that works in the same way that with an a iframe, you can see the example here:
https://jsfiddle.net/9zt976uz/2/#&togetherjs=nQoh3LINQG

canvasjs live updating data from database

I am new to web based visualization tool I used chartjs before but I did not find any solution for chartjs so, I transferred to canvasjs.Now I'm done creating the chart and it is successfully shown, thus I want to make it moving without refreshing because the data from the database is constantly moving. Here is my code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
window.onload = function () {
$.getJSON("json.php", function(result){
var dps= [];
//Insert Array Assignment function here
for(var i=0; i<result.length;i++) {
dps.push({"label":result[i].ts, "y":result[i].ph});
}
//Insert Chart-making function here
var chart = new CanvasJS.Chart("chartContainer", {
zoomEnabled:true,
panEnabled:true,
animationEnabled:true,
title:{
text: "myChart from mySQL database"
},
axisX:{
title: "TimeStamp"
},
axisY:{
title: "myDataPoints",
minimum: 0
},
data: [{
type: "spline",
dataPoints:
dps
}]
});
chart.render();
});
}
</script>
</head>
<body>
<div id="chartContainer" style="width: 800px; height: 380px;"></div>
</body>
</html>
now, I would like to ask for help out there What do I need to keep this chart moving...??
If you want the lines to move, you need to remove dataPoints from the beginning of the array. You can do so using shift function in JS.
for(var i=0; i<result.length;i++) {
dps.push({"label":result[i].ts, "y":result[i].ph});
dps.shift();
}
This would do the trick for you.

jqPlot : $.jqPlot is not a function error

I need to create charts on a website.
In my HTML code i have created a div with an ID.
This is my HTML code :
<script src="/js/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="/styles/jquery.jqplot.min.css" />
<script language="javascript" type="text/javascript" src="/js/jquery.jqplot.js"></script>
<script language="javascript" type="text/javascript" src="/js/graph.js"></script>
<body>
<div id="graph" style="height:400px;width:300px;></div> //i want to have my chart here
</body>
In the js code i have only wrote an exemple from the official website of jqPlot :
$(document).ready(function() {
var chart_data = [[[1, 2],[3,5.12],[5,13.1],[7,33.6],[9,85.9],[11,219.9]]];
var chart_opt = {
title:'Graph',
axes:{yaxis:{min:-10, max:240}},
series:[{color:'#5FAB78'}]
};
$.jqplot('graph', chart_data, chart_opt);
});
So my problem is that i have an error on the browser's console : $.jqplot is not a function
Any idea ?
You are getting this error because you have the jqplot inside the $(document).ready(function(). Try something like this.
$(document).ready(function(){
GetChart();
});
function GetChart(){
var chart_data = [[1, 2],[3,5.12],[5,13.1],[7,33.6],[9,85.9],[11,219.9]];
$('#graph').jqplot([chart_data], {
title:'Default Bar Chart',
seriesDefaults:{
renderer:$.jqplot.BarRenderer
},
axes:{
xaxis:{
renderer: $.jqplot.CategoryAxisRenderer
}
}
});
}
Here is a working example - https://jsfiddle.net/xrnfqax3/
For this example to work, you will need to add the following references to your project-
jquery.min.js
jquery.jqplot.js
jquery.jqplot.css
jqplot.barRenderer.js
jqplot.barRenderer.min.js
jqplot.categoryAxisRenderer.js
jqplot.categoryAxisRenderer.min.js
Make sure that jquery-*.js order is before jqPlot.js.
and use language="javascript" type="text/javascript" on all scripts tag.
Best Regards

JavaScript / JQuery to load JSON data into HTML5 dynamic drop-down

I have been trying to get this right and nothing I am doing is working. I made a hard-coded version of a dynamic drop down menu where the second field (State) provides information based on conditions set forth by the selection of the first field (Country).
Here is the hard coded html and JavaScript file:
form.html
<!DOCTYPE html>
<html lan="en">
<head>
<!-- <script type="text/javascript" src="sampleForm.js"></script>-->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript" src="sampleForm.js"</script>
<meta charset="UTF-8";
<title>Select Country and State</title>
<link rel="stylesheet" href="formStyle.css" />
</head>
<body>
<form id="sampleForm" enctype='application/json'>
<option id='country'>Select Your Country</option>
</form>
</body>
</html>
populate.js:
function populate(s1,s2){
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML="";
if(s1.value=="Canada"){
var getStates = ["|","alberta|Alberta", "britishColumbia|British Columbia", "manitoba|Manitoba", "newBrunswick|New Brunswick", "newfoundlandAndLabrador|Newfoundland and Labrador", "northwestTerritories|Northwest Territories", "novaScotia|Nova Scotia", "nunavut|Nunavut", "ontario|Ontario", "princeEdwardIsland|Prince Edward Island", "quebec|Quebec", "saskatchewan|Saskatchewan", "yukonTerritory|Yukon Territory"];
} else if(s1.value=="Pakistan"){
var getStates = ["|","balochistan|Balochistan", "northWestFrontierProvince|North-West Frontier Province", "punjab|Punjab", "sindh|Sindh", "islamabadCapitalTerritory|Islamabad Capital Territory", "federallyAdministeredTribalAreas|Federally Administered Tribal Areas"];
} else if(s1.value=="USA"){
var getStates = ["|","alabama|Alabama", "alaska|Alaska", "arizona|Arizona", "arkansas|Arkansas", "california|California", "colorado|Colorado", "connecticut|Connecticut", "delaware|Delaware", "districtOfColumbia|District of Columbia", "florida|Florida", "georgia|Georgia", "hawaii|Hawaii", "idaho|Idaho", "illinois|Illinois"];
}
for(var myState in getStates){
var pair = getStates[myState].split("|");
var newOption = document.createElement("option");
newOption.value = pair[0];
newOption.innerHTML = pair[1];
s2.options.add(newOption);
}
}
I have a JSON file that has Country keys and State values. I want to call the keys and values into the dropdown menu options. Based on the answer I found at
$(document).ready(function() {
var data = countryState.json;
var $selectCountry = $("#country");
$.each(data.d, function(i, el) {
console.log(el);
$selectCountry.append($("<option />", { text: el }));
});
});
Here is the new html file:
<!DOCTYPE html>
<html lan="en">
<head>
<!-- <script type="text/javascript" src="sampleForm.js"></script>-->
<!-- <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> -->
<script type="text/javascript" src="getData.js"></script>
<script type="text/javascript" src="moreScript.js"></script>
<meta charset="UTF-8";
<title>Select Country and State</title>
<link rel="stylesheet" href="formStyle.css" />
</head>
<body>
<form id="locationSelector" enctype='application/json'>
<br id="selectCountry"></br>
<select id='country'></select>
<br id="selectState">=</br>
<select id='state'></select>
</form>
</body>
</html>
Here is a JavaScript file referenced by the html file:
$(document).ready(function() {
var data = "countryState.JSON";
var $selectCountry = $("#country");
$.each(data.d, function(i, el) {
console.log(el);
$selectCountry.append($("<option />", { text: el }));
});
});
Here is the JSON file:
http://learn.ryanschostag.com/json-file-of-countries-and-states/
My new JavaScript file is based on the answer by Andrew Whitaker at I need help populating my dropdown with my JSON response.
My JSON file was found at gitHub.
I have tried making the src of my form the JSON file. I tried a lot of things for about an hour now, and can't get the data to populate to the drop-down menus, let alone make them dynamic based on conditions.
I don't know how to code the conditions if / else statements and functions relating to calling the JSON data and passing it to the drop down options.
Please help!
Thank you!

Errors when I use a fancytree instance

I am a newbie of using fancytree. I have created a demo to display data in a table within a webpage. Now I hope to collect the data back after users updated them.
I was using so called tree methods as mentioned in the tutorial. There is an example that has two lines below:
var tree = $("#tree").fancytree("getTree");
alert("We have " + tree.count() + " nodes.");
I thought I can use the fancytree instance, the variable 'tree' in the above example, to access all nodes so that to collect the values they take. But when I put this two-lines example into my codes, I got errors.
For making it clear, I pasted the complete code below. Close to the end of the code, there are two comments marked by Place_1 and Place_2. When I put the two-lines example in each of these two places, I got errors, which are "Uncaught TypeError: undefined is not a function", or "Uncaught Error: cannot call methods on fancytree prior to initialization; attempted to call method 'getTree'" respectively.
I thought I must missed something. Any idea will be helpful. Thanks!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<link type="text/css" rel="stylesheet" href="addtionals/jquery-ui.css" />
<script src="addtionals/jquery.min.js" type="text/javascript"></script>
<script src="addtionals/jquery-ui.min.js" type="text/javascript"></script>
<link href="fancytree/src/skin-win8/ui.fancytree.css" rel="stylesheet" type="text/css">
<script src="fancytree/src/jquery.fancytree.js" type="text/javascript"></script>
<script src="fancytree/src/jquery.fancytree.edit.js" type="text/javascript"></script>
<script src="fancytree/src/jquery.fancytree.table.js" type="text/javascript"></script>
<script type="text/javascript">
var Rigid_Package_SOURCE = [
{title: "Role-Based Statements", key: "1", folder: true, expanded: true, children: [
{title: "Text1", key: "2"},
{title: "Text2", key: "3"}
]}
];
$(function(){
$("#RB_Statements_tree").fancytree({
source: Rigid_Package_SOURCE,
extensions: ["edit", "table"],
edit: {
triggerCancel: ["esc"],
triggerStart: ["f2", "dblclick", "shift+click", "mac+enter"],
beforeEdit: function(event, data){
if (data.node.isFolder() ) {
var title = data.node.title;
data.node.editEnd();
data.node.setTitle(title);
return false;
}
},
beforeClose: function(event, data){
if (data.node.isFolder()) {
}else{
if (data.input.val() == ""){
data.node.setTitle("");
}
}
}
},
table: {
indentation: 20,
nodeColumnIdx: 1
},
renderColumns: function(event, data) {
var node = data.node,
$tdList = $(node.tr).find(">td"),
$select = $("<select />");
if( node.isFolder() ) {
}else{
$("<option > Tutor </option>").appendTo($select);
$("<option selected > Student </option>").appendTo($select);
$("<option > Teacher </option>").appendTo($select);
$tdList.eq(0).html($select);
}
}
});
});
</script>
</head>
<body>
<script type="text/javascript">
//Place_1: Uncaught TypeError: undefined is not a function
//var tree = $("#RB_Statements_tree").fancytree("getTree");
//alert("We have " + tree.count() + " nodes.");
</script>
<!--The title of this page-->
<h4> Vicarious Conversation</h4>
<!-- Table: Role-Based Statements -->
<table id="RB_Statements_tree">
<colgroup>
<col width="100px">
<col width="300px">
</colgroup>
<thead>
<tr> <th></th> <th></th>
</thead>
<tbody>
</tbody>
</table>
<br>
<script type="text/javascript">
//Place_2: Uncaught Error: cannot call methods on fancytree prior to initialization; attempted to call method 'getTree'
//var tree = $("#RB_Statements_tree").fancytree("getTree");
//alert("We have " + tree.count() + " nodes.");
</script>
</body>
</html>
Thanks for the suggestion from Chase.
I think the two-lines example should be added into somewhere after the initialization has been finished.
For example, I added the codes into a button's body and it works well. Here is the example about implementing a button in fancytree: http://wwwendt.de/tech/fancytree/demo/#sample-source.html

Categories

Resources