I have a program which is pulling data from the database like so.
Views.py
def final(request):
total = []
name = []
k = 0
for i in Question.objects.raw("SELECT name, question1, question2, question3, question4, question5, question6, question7, question8, question9, question10 FROM music_question"):
name.append(str(i.name))
total.append(int(i.question1) + int(i.question2) + int(i.question3) + int(i.question4) + int(i.question5)
+ int(i.question6) + int(i.question7) + int(i.question8) + int(i.question9) + int(i.question10))
return render(request, 'music/final.html', {"totals": total, "names": name, "rows": Question.objects.all()})
From here I'm trying to print into HTML like so
final.HTML
</body>
<script type=text/javascript>
data = {{totals}}
console.log(data)
</script>
</html>
I can see that the data from the database has returned to the console in Chrome but it won't persist onto the web page and I'm not sure where I'm going wrong.
Maybe you should put data = {{totals}} before </body> tag, or I did not understand you ?
Related
I want to change the HTML content of my webpage from within a javascript function. My HTML looks like this:
<div class="chartInfo">
<p id="last_updated">Hello</p>
</div>
My Javascript function is a QueryResponse to a GoogleCharts query. It looks like this:
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
function function_1() {
var queryString = encodeURIComponent('SELECT AA, AB');
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1dXP9yGEzNlmRxwCr2kyMM9CcS5hloIxKvef0RSa10/gviz/tq?gid=559927965&headers=1&tq=' + queryString);
query.send(function_2);
};
function function_2(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
};
var data = response.getDataTable();
var t = (data.getvalue(0,0));
var latest_time = t.getDate()
document.getElementById("last_updated").innerHTML = "Last updated: " + latest_time;
};
</script>
Currently the webpage is showing "Hello" rather than "Last Updated: " + latest_time as I want it to.
I think it may be a problem of scope - when I write scripts out underneath I can change it from "Hello" to another string using document.getElementById, but then I can't access the variable latest_time which is within function_2.
Thanks in advance for any help!
Change dom.innerHTML to dom.textContent for changing text of it
I'm having a problem getting data from my fetch response into a div. The data comes into the console just fine, but I can't get it to update the div.
<html lang="">
<head>
<meta charset="UTF-8">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div id="phand">
<button id="deal" class="btn">Deal!</button>
</div>
<script type="text/javascript" src="{% static 'blackjack/play.js' %}"></script>
</body>
</html>
(function () {
function deal() {
fetch('/deal')
.then(response => response.json())
.then(data => {
console.log(data)
var card1Rank = data[0];
var card1Suit = data[1];
var card2Rank = data[2];
var card2Suit = data[3];
$("#phand").append('<acidjs-xdeck-card rank=' + card1Rank + 'suit=' + card1Suit + '></acidjs-xdeck-card>');
});
};
$('#deal').on('click', function() {
deal();
});
}());
I want the javascript to insert the response from the fetch request into the "phand" element on the page, I can see the data coming through in the console, but it doesn't alter the contents of the page.
maybe you need to convert data to string with JSON.stringify() , try to append like
$("#phand").append('<acidjs-xdeck-card rank=' + JSON.stringify(card1Rank) + 'suit=' + JSON.stringify(card1Suit) + '></acidjs-xdeck-card>');
The problem was that I had the "phand" div inside another "wrapper" div.
I changed the js to:
$('#wrapper').find('#phand').append('<acidjs-xdeck-card rank=' + JSON.stringify(card1Rank) + 'suit=' + JSON.stringify(card1Suit) + '></acidjs-xdeck-card>');
and it worked as expected.
<html>
<body>
<div id="output">hi</div>
</body>
<script>
var link="http://mywp.com/cilacap/api/get_posts/";
var jcontent= JSON.parse(link);
var output=document.getElementById('output');
output.innerHTML=jcontent.id' ';
</script>
</html>
It only shows "hi".
Can someone tell me how to show JSON items such as "id" and "postDate"
with looping but without PHP scripting?
Thanks
Few syntactical errors, below is the right one.
<html>
<body>
<div id="output">hi</div>
</body>
<script>
var link='{"url":"http://mywp.com/cilacap/api/get_posts/", "id":"url_id_01"}';
var jcontent= JSON.parse(link);
var output=document.getElementById('output');
output.innerHTML=jcontent.id + ' ';
</script>
</html>
JSON Data(var link), was not parsable.
JSON Data(var link), didnt contained any attribute called id.
String concatenation in last line(output.innerHTML), was wrong.
Try removing the quotes from:
output.innerHTML=jcontent.id' ';
and change it to:
output.innerHTML += jcontent.id;
Providing that the link is valid it should work now.
You can also write:
console.log(jcontent);
and check if the console displays the value, or any errors that have occurred.
That url is a string, not json.
Use Ajax to get the data ( using jquery)
var link;
$.ajax({
url: "test.html",
}).done(function(data) {
link = data;
});
Then, extract the data;
output.innerHTML=jcontent.id;
Is for the value. You get the key like this:
ES7
Object.entries(jcontent)
.forEach(keyValuePair =>
{
// Push to HTML
var t = document.createTextNode(keyValuePair[0] + ' : ' + keyValuePair[1]); // Create a text node
output.appendChild(t);
});
ES6
Object.keys(jcontent)
.map(key => [key, jcontent[key]])
.forEach(keyValuePair =>
{
// Push to HTML
var t = document.createTextNode(keyValuePair[0] + ' : ' + keyValuePair[1]); // Create a text node
output.appendChild(t);
});
ES5 (Most likely your case)
Use function instead of arrow functions for es5:
Object.keys(jcontent)
.map(function(key){ [key, jcontent[key]] })
.forEach(function(keyValuePair)
{
// Push to HTML
var t = document.createTextNode(keyValuePair[0] + ' : ' + keyValuePair[1]); // Create a text node
output.appendChild(t);
});
Access the value:
keyValuePair[0] // key
keyValuePair[1] // value
Ps
If you want to use the es7 or es6 method, have a look at babeljs
I have a HTML file that uses some JScript that I found online and would like it to incorporate it into a simple page for internal use that can be used to quickly look up information.
The page would present the data from a JSON file that is stored on the server.
I can add the JSON data directly to the HTML file, but would like a file that we can export from time to time in-place with the new data and now have to manually edit the HTML files directly.
So far I have this HTML file:
<html>
<head>
<script type='text/javascript'>//<![CDATA[
$(function(){
var a = ['https://url.com/data.json'];
jQuery('#search-json-submit').click(function() {
jQuery('#search-output').html('');
var search_query = jQuery('#search-json-input').val();
var search_query_regex = new RegExp(".*"+search_query+".*", "g");
jQuery.each(a, function(k, v) {
if(v['name'].match(search_query_regex) ||
v['id'].match(search_query_regex) ||
v['location'].match(search_query_regex)) {
jQuery('#search-output').append('<li>Search results found in: '+'{ name: "'+v['name']+'", id: "'+v['id']+'", location: "'+v['location']+'" } </li>');
}
});
});
});//]]>
</script>
</head>
<body>
<input type="text" id="search-json-input" />
<input type="button" id="search-json-submit" value="search" />
<h4>Search Results</h4>
<ol id="search-output">
</ol>
</body>
</html>
My JSON file is the following text:
{"name":"mynewname", "id" : "t2", "location" : "India"},
{"name":"mynewname1", "id" : "t21", "location" : "China"},
I am not sure what I am doing wrong to link the variable a to the JSON file URL to search.
I had a look at another page and it linked the JSON file using
$.getJSON('https://url.com/data.json')
but I can't get that to work either.
The original a variable for this example is:
var a =[
{"name":"mynewname", "id" : "t2", "location" : "India"},
{"name":"mynewname1", "id" : "t21", "location" : "China"},
];
Once I get the search function to work, I can then format it properly and find a more suitable solution in the long term. For now I would like to just kick start this and get it up and running.
Try
$(function () {
jQuery.getJSON("data.json", function (a) {
jQuery('#search-json-submit').click(function () {
jQuery('#search-output').html('');
var search_query = jQuery('#search-json-input').val();
var search_query_regex = new RegExp(".*" + search_query + ".*", "g");
jQuery.each(a, function (k, v) {
if (v['name'].match(search_query_regex) || v['id'].match(search_query_regex) || v['location'].match(search_query_regex)) {
jQuery('#search-output').append('<li>Search results found in: ' + '{ name: "' + v['name'] + '", id: "' + v['id'] + '", location: "' + v['location'] + '" } </li>');
}
});
})
});
});
Make sure that data.json is located on same server(domain) as your js/html(cross origin policy).
Update: http://jsfiddle.net/m7jocxwh/1/
I have a product list that is generated by asp
I have product description for each product in a html file
each html file is named: <product.id>.html<br/>
html file size is only 1-3 kb
Within the html file is <title> and <meta name="description" content="..." />
I want to access these in an efficient way so that I can output this as e.g.:
document.write(<product.id>.html.title);<br/>
document.write(<product.id>.html.description);
I have a working solution for the individual product, where I use the description file - but hope to find a more efficient / simple approach. Preferably, I want to avoid having 30+ hidden iframes - google might think that I am trying to tamper with search result and blacklist my page...
Current code:
<iframe src="myfile.html" id="product" style="display:none"> </iframe>
<script type="text/javascript">
document.getElementById('product').onload = function(){
var d = window.frames[frame].document;
var title = d.title : ' ';
var keywords = d.getElementsByName('keywords')[0].getAttribute('content', 0) : ' ';
var descript = d.getElementsByName('description')[0].getAttribute('content', 0) : ' ';
}
</script>
As mentioned here on another Stack Overflow question, you could use:
document.title = "This is the new page title.";
and looking here gives us :
document.getElementsByTagName('meta').content = "New content here";
or:
document.getElementsByTagName('meta').name = "NewName";
With these, you should be able to read and write your tags as needed, I've only used a few examples here, there's surely more.
You could load your files with AJAX. For example (using jQuery):
$.get('myfile.html', function(data){
var title = $(data).find('head title').text();
var keywords = $(data).find('head meta[name="keywords"]').attr('content');
var descript = $(data).find('head meta[name="description"]').attr('content');
});
Here you find the jQuery documentation about using jQuery.get
Found this solution:
<script>
var xhr = $.ajax({
type: "GET",
url: "/files/billeder/ecom/beskrivelser/<!--#Ecom:Group.Number-->.html",
success: function(msg){
msg = msg.split('content="')[1];
msg = msg.split('"')[0];
document.getElementById("a_<!--#Ecom:Group.Number-->").innerHTML = "<p>" + msg + "</p>";
Not yet very elegant... but it works...