Display The Result Of a SQL Query Using Javascript - javascript

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.

Related

How to call a JavaScript function in HTML on load

JavaScript code I am trying to get to call from the HTML.
var ClassList = new Array ["Bio1300","csci12"];
function ClassMenu(ClassList) {
return (ClassList.toString);
};
This is the HTML code I am trying to call the JavaScript function inside of on the load of the page.
<li>
<script type="text/javascript" src="JavaScript InProg.js">
function ClassMenu() {
console.log(ClassList.toString);
}
</script>
</li>
Please help. I have many other functions I am trying to call in this manner that are both arrays and contain mathematical calculations.
There are a few issues with the code snippet you've provided. Firstly, it's considered a best practice to add your <script> tags inside the <head> of the document or at the end of the document when loading JavaScript files. Secondly, your source reference is incorrect. Assuming the JavaScript file InProg.js is at the same directory level as your HTML file, you could change your script link to something like this:
<script src="InProg.js"></script>
Once you've ammended how you're loading the JavaScript file into your page, you can simply make a call to the function inside another <script> tag from anywhere on the page, like so:
<script>ClassMenu(params);</script>
Also, I'd recommend adding the console.log statement to the function you're calling.
Hopefully this helps.

Display JSON in Javascript from Python Bottle

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.

Change Text using jQuery

I have a script that is pulling in news from Yahoo on a certain subject. It renders the title of the news feed like this:
<div class="header-title">subject - Yahoo! News Search Results</div>
I would like to change this to read differently. Since this is inserted via JS I thought I could change this with jQuery.
I attempted this:
$('.header-title').text('Subject News');
that did not work, I then attempted this:
$('.header-title').empty();
$('.header-title').text('Subject News');
that also did not work.
Both of the above methods look as if they had no effect on the text.
I am not sure what to do to remove the old text and replace with my text.
Note: All of my code is inside jQuery's Document Ready IE:
$(function(){
//Code Here
});
Don't forget to put your code in DOM ready:
$(function() {
$(".header-title").text("Subject News");
});
Otherwise the code should work fine.
This solution assumes you have no access to the other script that creates the feed widget
WIthout knowing more about other script it sounds like it is asynchronous, and creates the title elements also. You could have a timed interval loop that checks for the element to exist and once it exists do the update:
function changeYahooTitle(){
var $yhooTitle=$('.header-title');
if($yhooTitle.length){
$yhooTitle.text('My New Title');
}else{
/* doesn't exist so check again in 1/10th second, will loop recursively until found*/
setTimeout(changeYahooTitle, 100);
}
}
Then on page load:
$(function(){
changeYahooTitle()
})
If you do have access to the other script it can be modified to accommodate your needs, or you can still use this solution
Try using html() instead of empty() and text()
$(document).ready(function(){
$(".header-title").html("Subject News");
});
What's probably happening:
First you're setting the text: $('.header-title').text('Subject News');
THEN ... after the data finishes the load of the Yahoo or whatever content your text gets replaced actually with the new fetched data
Change the text inside the load callback (after data is loaded) and it will work.
It doesn't work because you call the function before the element is created. If you put your function inside <script> tag after the <div> element it should work

how to re-factor/extract methods to separate file for re-use

I'm fairly new to the whole JQuery/javascript world, but I've managed to wack together a working jqgrid with a datepicker & custom control (used jquery auto complete) based on code samples i found on the net. I've added the code to a T4 template in my project as it'll probably act as a base/starting point for most pages. (Side note. I'm using asp.net MVC)
JFIDDLE: LINK
1.) I'd like to move the initDateEdit & initDateSearch to the same function (using a parameter, to disable/enable the showOn property) as they are basically similar.
2.) How would be the best way to set nonWorkingDates from outside the new function/file. same applies to the autocomplete_element (I'd like to specify the url)
Changing
"function nonWorkingDates(date)" to => "function nonWorkingDates(date, nonWorkingDates)"
isn't working, (guess it's got got something to do with how its gets called "beforeShowDay: nonWorkingDates")
Thanks in advance!
If you have a chunk of JS code like this:
<script type="text/javascript">
... code goes here ...
</script>
You simply copy the whole thing, eliminate the containing script tags, and save the raw code
... code goes here ...
to a file, which you then include with:
<script type="text/javascript" src="yourfile.js"></script>
However, since you're using jquery, you'll have to make sure that this above snippet is placed AFTER the script tag that loads up jquery, or you'll get a "no such function" syntax error.

jQuery objects don't work

When I store a jQuery object in a variable, like this:
var $myObject = $("div#comments");
...I can't use the object $myObject!
This is what I'm doing to change the html of div#comments:
$myObject.html(data);
It does nothing. I already tried this way too, this time to select an element inside div#comments:
$("div.comment", $myObject);
It doesn't work.
I just want to be able to save an element in a variable and then use it!
Note: some people don't put $ before the variable name, like this: myObject.
Are you calling it after the document is loaded?
// This will ensure that the code doesn't run until
// the document has loaded
$(function() {
var $myObject = $("div#comments");
});
(This is a shortcut for jQuery's .ready() method.)
http://api.jquery.com/ready/
As long as the document is loaded, and you have a <div> with the ID comments on the page when it loads, it should work.
Also remember that there can only be one element on the page with any given ID. Because of this, it is actually a little better (quicker) to do $("#comments"); instead of $("div#comments");.
You've only provided snippits of your code, so it is impossible to tell for sure, but the odds are that you are running the code in a <script> element that appears before the <div> element and don't do anything (such as use the ready event) to delay the execution of the code until the div exists.
The result is that you get a jQuery object which found no elements. Move the script element so it is after the div. Just before the end tag for the body is a good place.
The syntax is perfectly valid and should work. Are you dynamically appending the comments div? You should alert( $myObject.length ) to see if it's 0 or 1, if its 0 that means it's never picked up.
You may need to bind the var statement until after dom ready, window load, or your ajax callback.
Well, that syntax is perfectly fine so something else is going on. Can you show your markup? And what do you get if you add an alert($myObject.length)? And one last thing to check... are you running this inside an on-ready handler?
Ok, thanks everyone for that.
I got the solution.
I thought about the order the things were loaded in the DOM and found the solution.
The problem (with the markup) was:
<div id="comments">
<script type="text/javascript">
loadComments(params);
</script>
</div>
The code above was written by PHP!
So it executed the function as soon as the browser read the code.
I already tried to put the script on the end of the page, after the function was called. The funcion was not defined yet.
So, the funcion loadComments should be executed after the div was ready AND after the function was defined.
I wrapped the code between the tags with a .ready(), like this:
<script type="text/javascript">
$(function() {
loadComments(params);
});
</script>
It was a distraction.
Sorry everyone!
Thanks a lot.
If you have the same problem and you didn't understand what I did, ask me. XD

Categories