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/
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 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 ?
<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 am kind of new to writing code and using API's. I am not entirely sure why my program is not working the way I would like it to.
What I want this to do is provide the search results in the console before I can move onto what I would like it to do next; however, I don't think anything is being searched.
According to this: https://developers.google.com/youtube/v3/docs/search/list#http-request, the only required parameter is "part," so I think I did everything right? Probably not though, because from what I can tell, nothing is being searched when I try to search for a term.
Here is my code:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<section>
<form id="search-term">
<p>Enter Name:<br/>
<input id="query" type="text" name="Name"/><br/>
<hr/>
<input type="button" value="Enter here"/>
</p>
<div id="search-results">
</div>
</form>
</section>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</body>
</html>
JavaScript:
$(document).ready(function(){
$('#search-term').submit(function(event){
event.preventDefault();
var searchTerm = $('#query').val();
getRequest(searchTerm);
});
function getRequest(searchTerm){
var params = {
"q": "searchTerm",
"part": 'snippet',
"type": 'video',
"key": 'I was advised to keep my key private, so I edited this part out'
}
url = 'https://www.googleapis.com/youtube/v3/search';
$.getJSON(url, params, function(data){
showResults(data.items);
})
}
function showResults(results){
var html = "";
$.each(results, function(index,value){
html += '<p>' + value.snippet.thumbnails.high.url + '</p>' + '<p>' + 'https://www.youtube.com/watch?v=' + value.id.videoId + '</p>' + '<hr/>';
console.log(value.snippet.thumbnails.high.url);
console.log(value);
})
$('#search-results').html(html);
}
})
You probably want data.items instead of data.search
I don't see any mention of a 'search' parameter under the "Response" section listed in their documentation. See the response properties here: https://developers.google.com/youtube/v3/docs/search/list#response
Therefore, you can probably see some output if you console.log(data); instead of data.search
I recommend you check out Google's Javascript API Client Library. It might not be the best solution for you, but it's worth a try. Download on GitHub
Example using gapi.client.youtube.search.list:
// After the API loads, call a function to enable the search box.
function handleAPILoaded() {
$('#search-button').attr('disabled', false);
}
// Search for a specified string.
function search() {
var q = $('#query').val();
var request = gapi.client.youtube.search.list({
q: q,
part: 'snippet'
});
request.execute(function(response) {
var str = JSON.stringify(response.result);
$('#search-container').html('<pre>' + str + '</pre>');
});
}
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...