I am trying to access a mongodb record within a javascript function to display the document on a webpage. Using the Bottle framework with pymongo, I have tried to first encode the mongodb document as a JSON object to pass to my javascript function.
#bottle.route('/view/<_id>', method = 'GET')
def show_invoice(_id):
client = pymongo.MongoClient("mongodb://localhost")
db = client.orders
collection = db.myorders
from bson.objectid import ObjectId
result = collection.find_one({'_id': ObjectId(_id)})
temp = json.dumps(result,default=json_util.default)
print "temp: " + temp
return bottle.template('invoice', rows = temp)
When I try to display the document within my HTML page with the javascript function, nothing happens. However, when I call the variable, rows, that I am trying to pass as {{rows}} within the body of the HTML it does display. It seems it is only the JS function that does not display anything.
<!DOCTYPE html>
<html>
<head>
<head>
<title>Invoice Report</title>
<script type="text/javascript">
function fillTable()
{
var obj = {{rows}};
document.write(obj);
}
</script>
</head>
</head>
<body onload="fillTable()">
<div class="invoice">
</div>
<h4>Rows from body</h4> {{rows}}
</body>
</html>
I tried to use jQuery to deserialize the JSON object rows with the function
jQuery.parseJSON(rows);
and even as
jQuery.parseJSON({{rows}});
I also tried to make the variable unescaped everywhere possible as {{!rows}}
So does anybody see what I am doing wrong? How do I take a mongodb document with pymongo, and use bottle to display it on a webpage? I realize that similar questions have been asked, but I can't seem to get anything I have found to work in my particular situation.
The issue isn't with bottle rendering your json, it's with using document.write().
Open a new tab in your browser, and point it to the url: 'about:blank'. This will give you a blank webpage. Now, right click and open your developer tools. Try running document.write('Stuff'); from that context. You shouldn't see any changes to the page.
Instead try:
var body = document.getElementsByTagName("body")[0];
body.innerHTML = "Stuff";
and note the difference.
There are of course, many other ways to achieve this effect, but this is the simplest without any requirements on external javascript libraries.
You can't have both an 'src' attribute and javascript code in the same tag. Place the fillTable function within a new script tag.
Related
so on my index.html page i have dynamic objects created by using appendChild and each one of them has an onclick function. I am able to grab a value when clicked. but if i want to use this value and show it on another html page, how can i do this? i am using plain javascript.
from first.js for first html
var cardTitle = document.createElement("div");
cardTitle.setAttribute(`onclick`, 'function(this)');
var title = document.createElement("h2");
title.textContent = thing.data().title;
cardTitle.appendChild(title);
tohtml.appendChild(cardTitle);
from second.js for second html
function function(test){
window.location.href = "second.html";
let title = test.firstChild.textContent;
document.getElementById("id").innerHTML = title;
}
so i honestly dont know if am even suppose to code like this with two js and two html. i do see some errors here and there but it works. if there are better ways of doing this, please let me know, if it isnt difficult to apply.
i just have dynamically loaded objects from database loaded on one html and when clicked, i need to grab some values of the clicked object and show them on another html or maybe somehow use them.
so as said, i did get a hold of "thing.data().title" but just cant get it to display on second html.
please help...
thanks in advance!!!
I'm afraid you cannot transfer information from one html page to another that easily.
What you could do however is saving the data in the browser's local storage and retrieve it from there on your second html page.
Here's a sample.
Save this as page1.html
<html>
<head>
<script type="text/javascript">
var text = prompt("Enter some text:");
localStorage.setItem('myText', text);
</script>
<button onclick="window.open('page2.html','_blank')">Click</button>
</head>
</html>
and this as page2.html
<html>
<head>
<script type="text/javascript">
document.write("You have written: " + localStorage.getItem('myText'));
</script>
</head>
</html>
If you open page1 it will prompt you to enter some text. Afterwards push the 'click' button to open page2 in a new browser window where you'll see what you've entered in page1.
I'm looking to solve the issue of not being able to Save/Apply changes to an .html document when the document.createElement("div"); is used in JavaScript. I want to be able to save the changes made to the document and 'overwrite' the original .html document.
Future Possibilities(these can be ignored):
Deletion of these elements, and saving those changes as well to revert it back to it's original state.
EDIT: --------------
I didn't make this clear, sorry!
THIS CODE IS TO EMBED MULTIPLE YOUTUBE VIDEOS ON A SINGLE PAGE; I WOULD LIKE SOME HELP HAVING SOMETHING OVERWRITE THE ORIGINAL .HTML DOCUMENT. THEREFORE LOADING THIS NEW CONTENT EACH TIME SOMEONE OPENS THE PAGE.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div id="container">
<div id="header" align="center">Home</div>
<div align="center">
<button onclick="myFunction()">Button</button>
</div>
<div id="parentElement" align="center">
</div>
<script>
function myFunction() {
var parentElement = document.getElementById('parentElement');
var theFirstChild = parentElement.firstChild;
var newElement = document.createElement("div");
parentElement.insertBefore(newElement, theFirstChild);
newElement.setAttribute("id", "newElement");
var embed = prompt("Please enter your YouTube Embed Link");
if (embed != null) {
document.getElementById("newElement").innerHTML = embed;
}
}
</script>
</body>
</html>
I think what you're asking is how to put dynamic content in a static web page. This is not my area of expertise, but I can give you the outlines of how to do what you're trying to do. This is the architecture. You'll have to fill in some implementation details yourself, but I'll try to give you a clear idea of what you'll be googling for at each step of the way.
Suggestions for improvement from real web guys will be eagerly embraced. If there's already an answer on SO that walks a noob through the design of a trivial single-page AJAX/JSON web app, I can't find it. There must be one, though.
This is a lot more complicated than your original idea, but rewriting a web page not a great idea: You're writing arbitrary zeroes and ones from strangers to a file on your server. You need one HTML file per user, if you store their data in HTML files. How do you serve him the right one? What if you change the layout after you have 500 users? You'd be writing a script to alter the text of 500 HTML files. In practice it's just a horrorshow.
What you're groping for is dynamic content via AJAJ, which we usually still call AJAX for historical reasons (prior to the advent of CNC machining, curly braces were difficult to mass produce economically, and so web services commonly used pointy brackets instead).
First, write a web page to serve the user's personal content. It'll save updates as well. May as well use PHP. That "page" isn't a web page; instead of HTML, it returns JSON text with a content-type of application/json. The user can POST text to it in JSON format as well. This "page" is a web service.
On a get request, the web service page, given a username (and appropriate security), will retrieve the user's YouTube video list from MySQL and return it to the caller as JSON.
For now, the content going to and from that web service page is pretty simple. Just a list of URLs. Let's make it an object that has one member, and that one member will be an array of objects that contain information about YouTube videos the user has chosen. For now, each one just has a URL, but we may want to add more detail later, so we won't just make it an array of bare URL strings. At the top level, we'll also be able to add other types of content alongside "YouTubeVideos" if there's a need -- for example, you're going to want a username and a security token.
{
"YouTubeVideos": [
{
"url": "http://youtu.be/LKJDFKLJDF"
},
{
"url": "http://youtu.be/87sdfd234"
}
]
}
In the HTML page, your JS code will first request the user's data from that web service in onLoad. You'll do that using XMLHttpRequest. You'll use the JavaScript function JSON.parse to turn the response text into a JS object.
So write a function called requestUserYTContent or something, and call that from onLoad. This is simplified: There's no validation, exception handling, etc.
// Empty default instance to start out.
var ytInfo = { "YouTubeVideos" : [] };
function requestUserYTContent() {
// ...
// Do stuff with XMLHttpRequest to get the JSON for this user from
// the web service.
// ...
ytInfo = JSON.parse(http_request.responseText);
console.log('Got ' + ytInfo.YouTubeVideo.length + ' videos');
// Once you've got that JSON object, you can loop through the
// videos and do stuff with their urls. We'll stick that loop in
// another function so we can re-use it in cases where the list
// changes for reasons other than a web service call.
var ytDiv = document.getElementById('ytContent');
ytDiv.innerHTML =
generateVidListHTML(ytInfo.YouTubeVideos);
}
function generateVidListHTML(vids) {
var newHTML = '';
for (var i = 0; i < vids.length; ++i) {
var url = vids.YouTubeVideos[i].url;
// ...generate HTML to display this video, and append to
// newHTML
}
return newHTML;
}
So we keep that ytInfo around in a global variable. When the user adds to the list or deletes from it, alter the list, re-generate the HTML with generateVidListHTML(), insert the HTML into the page as above, and then post the newly-altered list as JSON back to the web server to update the user's content in the mySQL database.
You'll POST data back to the web service with XMLHttpRequest. Here's an example. You'd be using a different content-type, of course.
https://stackoverflow.com/a/9713078/424129
In JavaScript in the web page, converting a live JavaScript object back to JSON is easy: https://stackoverflow.com/a/4162803/424129
For simplicity, you may as well just pass the same JSON format back and forth.
When you send JSON back to the web service, it'll need to parse it too. I don't know how to parse JSON in PHP, but I know somebody who does:
https://www.google.com/search?q=how+to+parse+json+in+PHP
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div id="container">
<div id="header" align="center">Home</div>
<div align="center">
<button onclick="myFunction()">Button</button>
</div>
<div id="parentElement" align="center">
<div id="newElement" style="display: hidden"></div>
</div>
<script>
function myFunction() {
var embed = prompt("Please enter your YouTube Embed Link");
if (embed != null) {
document.getElementById("newElement").innerHTML = embed;
$('#newElement').css('display','inline');
}
}
</script>
</body>
</html>
just taking out the parent - child element relationship in javascript code and put the new element div in html with display:none style attribute. Then in click function, just make it visible.
Cheers!
It took sometime to understand your requirement infact still now it is not clear .But from your code I understand that you are trying to get a text from prompt message and initally you want to display it in your page.But that is not working since you are not able to execute it.
document.getElementById("newElement").innerHTML
Rather that using innerHTML you can check textContent.
Here is a minor change in your function
if (embed != null) {
newElement.textContent = embed;
}
WORKING COPY
I know this has been asked before but mine might be a little different.
I have an HTML page that I have little control of and has a restriction on what JavaScript can be used. In this HTML I decalare a variable, in this case an array of image URLs.
In an external file I am trying to use this variable. The variable works anywhere within this file, but as soon as I try and show it within document.ready it becomes undefined.
Making it awkward is that I can't call the external script without writing it in a document.write script (it's within eBay and you can't call external scripts easily)
Can anyone help with why it doesn't work, or a better way of doing it?
I have full control of the JavaScript file, but the HTML I have access to, but limited to what I can write in there without eBay blocking it. It's for this reason the document.write has to be used.
My code is like this (a stripped out version):
console.log("Images: " + prodImgs);
$(document).ready(function() {
console.log("Images inside doc ready: " + prodImgs);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<head>
<meta http-equiv="content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
var prodImgs = new Array();
prodImgs[0] = "http://example.com/Media/images/testImages/1.jpg";
prodImgs[1] = "http://example.com/Media/images/testImages/1.jpg";
prodImgs[2] = "http://example.com/Media/images/testImages/1.jpg";
prodImgs[3] = "http://example.com/Media/images/testImages/1.jpg";
prodImgs = prodImgs.filter(function(v) {
return v !== ''
});
document.write("<" + "script src='http://example.com/Scripts/jquery-1.8.1.min.js' type='text/javascript' " + "></" + "script><" + "script src='http://example.com/Scripts/myscripts.js' type='text/javascript' " + "></" + "script>");
</script>
</head>
<body>
If you view the source on eBay, they already reference jquery version 1.7, on the home page anyway.
http://ir.ebaystatic.com/rs/v/jmalt0eyvq1k1k2ezqntv51k5mo.js
Suggest there is possibly a conflict. I would strongly suggest not using jquery unless you must because you will be at the whim of whatever eBay decide to do with their general code base.
Using an iframe to embed the content or features would allow you to have independent code that won't clash with ebay's core, although you will potentially have cross-site scripting errors depending on what you are trying to achieve.
Perhaps a combination of both. I assume you are trying to embed a slide show. Have a iframe hosted elsewhere for that, and then keep to general content and pure javascript if you need.
Remember to use closures and limit globals as again you may conflict with ebays base code.
did you mean you want to declare a variable in your html page.
and want to access that variable in .js file?? if so then in html file when you declare a variable dont use the var keyword.
dont use this
var prodImgs=new Array();
use the below one
prodImgs=new Array(); -- use this.
now you can access the prodImgs variable in .js file
So,
I'm trying to build a simple bookmarklet that does a whole bunch of stuff based upon the source code (Which, itself, contains javascript.
Essentially, it's taking a number of bits of data from source which it grabs and and finds using regex queries and then manipulates.
I've got everything beyond the grabbing the source code... I just need some help figuring out the source bit.
So, what do I need to do to take the source code of the page I'm currently
document.documentElement.innerHTML will get you everything except the <html> tag itself and the <doctype>. But, this may not be the actual source code, as the html may have changed by some script. It may be better to get the source code via Ajax:
var xhr = new XMLHttpRequest();
xhr.open("GET", location.href, false);
xhr.send();
var source = xhr.responseText;
Once you get the object (with something like document.getElementById()), you can try using .innerHTML
For example
<html>
<head>
<title>Demo</title>
</head>
<body>
<div id="box">I want the code for this <span>html</span></div>
</body>
</html>
The javascript would run something like this
var data=document.getElementById('box').innerHTML;
Here's a demo in JSFiddle:
http://jsfiddle.net/LW2VH/
I've been reading a tutorial called Adding SQL Database support to your iPhone App(I use PhoneGap because I won't get on Objective-C), I've done that all, but now when I tried to display the result(celebsDataHandler) like this it shows nothing:
<script type="text/javascript" charset="utf-8" src="db.js"></script>
<script type="text/javascript" charset="utf-8">
document.write(celebsDataHandler);
</script>
What should I do to correct this problem?
celebsDataHandler appears to be a function, based on what the tutorial says. You can't document.write a function.
Have you tried using a more versatile command like console.log to see what the value of celebsDataHandler is?
Or, you may wish to change the last line of the function from
alert(html);
to
return html;
First, you need to have some part of your document set up to handle showing the celebrities, for this example. Make sure you have a DOM element in your HTML page that has an ID that you can reference, for example:
<div id="myCelebs"></div>
Next, change the last line of the celebsDataHandler function to:
document.getElementById('myCelebs').innerHTML = html;
Finally, in your inline script, change your document.write call to:
loadCelebs();
To recap what is going on:
The loadCelebs function contains the SQLite code that queries the database and retrieves your data. It references a callback function (in this case named celebsDataHandler) that is invoked once the data is ready to be parsed.
The celebsDataHandler callback function iterates over results and compiles celebrity data into HTML - which it then injects into the "myCelebs" DOM element.
Hope that helps.