Hi I am using flask to create a web app in python.
In my profile.html page in template direcotiry I have profile.html as shown below.
<!DOCTYPE html>
<html lang="en">
<head>
<title>App</title>
<link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">
<script src="../static/js/jquery-1.11.2.js"></script>
<script src="../static/js/getAcademic.js"></script>
</head>
<body>
<div class="jumbotron">
</div>
</body>
</html>
In the app.py,
#app.route('/getDetails')
def getDetails():
try:
#get data from mysql database and convert to a json and return
return json.dumps(academic_dict)
except Exception as e:
return render_template('error.html', error=str(e))
The returned json object is as follows,
In my js file,
$(function() {
$.ajax({
url: '/getDetails',
type: 'GET',
success: function(res) {
var div = $('<table>')
.attr('class', 'list-group')
.append($('<tr>')
.attr('class', 'list-group-item active')
.append($('<td>')
.attr('class', 'list-group-item-text'),
$('<td>')
.attr('class', 'list-group-item-text')));
var wishObj = JSON.parse(res);
var wish = '';
$.each(wishObj,function(index, value){
wish = $(table).clone();
$(wish).find('td').text(value.Title);
$(wish).find('td').text(value.Data);
$('.jumbotron').append(wish);
});
},
error: function(error) {
console.log(error);
}
});
});
json is converted and returned correctly but the data is not displaying in the profile.html page. I checked the console and it is displaying the error Uncaught ReferenceError: table is not defined in the .js file.
I want to display a table with the data returned as the json object but the table is not displaying when the profile.html page is loading. Please help me with this.
You've got one simple mistake (but don't worry, that happens to everyone...) on the line wish = $(table).clone(); – you use table to reference <table> you saved in variable div .
Either replace $(table) with $(div) there or (I would suggest this solution for readability) rename var div = $('<table>') in the beginning to var table = ...
(Sorry for reviving such an old post, but I'm on badge hunt :])
Oh, and one more point: please don't use screenshots of code, but the code itself (even just shortened) for us to test your problem and our solution:
[{'Title': 'Name', 'Data': 'john mark'},
{'Title': 'Faculty', 'Data': 'cs'}]`
Related
So I have this template named test.html:
mynameis: {{mynameis}}
I then have a controller with the following code:
$scope.mynameis = 'slim shady';
var newScope = $scope.$new();
var newElem = '<ng-src><div ng-include="\'./test.html\'" ></div></ng-src>';
var emailtext = angular.element(newElem);
var myres = $compile(emailtext)(newScope);
$timeout(function(){
console.log('OUTPUT',myres[0].innerHTML);
console.log('OUTPUT ALL',myres[0]);
var htmlEmaiBody = emailtext.html();
var ToRecipients = [{EmailAddress: {Address: 'myemail#gmail.com'}}];
var emailPayload = {Message: {Subject: 'subject',Body: {ContentType: 'Html',Content: '<b>manual html</b><br>'+htmlEmaiBody},ToRecipients: ToRecipients}};
Office365MailService().messages().sendOnFly(emailPayload).then(function () {
console.log('email sent');
}, function (error) {
console.log('email not sent');
console.log(error);
});
});
Office365MailService is only another function that sends a mail.
NB: This worked before. Some change must have been made, as it is not working anymore.
What I see in the console is:
OUTPUT <!-- ngInclude: './test.html' -->
But I also see the text "OUTPUT ALL" with this html-structure:
<ng-src class="ng-scope"><!-- ngInclude: './test.html' --><div ng-include="'./test.html'" class="ng-scope"><span class="ng-binding ng-scope">mynameis: slim shady</span></div></ng-src>
The mail I receive only contains the bolded "manual html".
I then have a look at the source of the message in my email client and I see this at the end:
Content-Type: text/html; charset="us-ascii"
Content-Transfer-Encoding: quoted-printable
<html>
<head>
<meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3Dus-ascii"=>
</head>
<body>
<b>manual html</b><br>
<!-- ngInclude: './views/matching/testTemplate.html' -->
</body>
</html>
Why? Isn't the template getting compiled or what? I'm doing this in the timeout as I learned you have to wait for the compile-function to be ready. But still, nothing from the test.html-template is included.
However, in the output to the console, the name "slim shady" was printed from the template. So the problem should NOT be that the template is not compiled and ready. What could it be?
The solution is to use a callback when loading the template.
$templateRequest(templateName).then(function(template) {
The code above is the first thing to do. Then in the callback you can use compile and timeout. Otherwise, with my old code, the compilation of the template was one on a template that could haven't been fetched yet.
SO it was an async-issue.
In a class, I was asked to make a dynamic drop-down menu in a form using HTML5 and JavaScript. I did that here.
Now, I need to call data from a JSON file. I looked at other answers on SOF and am still not really understanding how to use JQuery to get info from the JSON file.
I need to have 2 fields: the first field is a Country. The JSON key is country and the value is state. A copy of the JSON file and contents can be found here. The second drop-down field adds only the values / arrays related to its associated Country.
Here is a copy of my HTML5 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 copy of the JS file I wrote so far that tries to get the data from the JSON file and fails:
$(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 content from the other JS file that adds the field instruction:
var selectYourCountry = document.getElementById('selectCountry');
selectYourCountry.innerHTML = "Select Your Country: ";
var selectYourState = document.getElementById('selectState');
selectYourState.innerHTML = "Select Your State";
This was supposed to at least add the values to the field, but nothing but empty boxes appear on the web page.
I then need to make a conditional statement like the one at here but calling or referencing data from the JSON file.
I have only taken some HTML and JavaScript courses, not JQuery and JSON. So, your help will greatly increase my knowledge, which I will be very grateful for.
Thank you!!
I found this SOF answer and changed my JS file to the following:
$(document).ready(function()
{
$('#locationSelector').click(function() {
alert("entered in trial button code");
$.ajax({
type: "GET",
url:"countryState.JSON",
dataType: "json",
success: function (data) {
$.each(data.country,function(i,obj)
{
alert(obj.value+":"+obj.text);
var div_data="<option value="+obj.value+">"+obj.text+"</option>";
alert(div_data);
$(div_data).appendTo('#locator');
});
}
});
});
});
And, I edited my HTML document as follows:
<form id="locationSelector" enctype='application/json'></form>
I removed and added back the <select> tags and with the following at least I get a blank box:
`<form id="locationSelector" enctype='application/json'>
<select id="locator"></select>
</form>`
I feel like I am getting closer, but am still lost.
Can you try this:
$.get("countryState.JSON", function( data ) {
var html = "";
$.each(data.d, function(i, el) {
console.log(el);
html += "<option value='"+Your value+"'>"+Your displayed text+"</option>";
});
$('#state').html(html);
});
I am new to programming and recently began learning Javascript, I have a problem that appeared in few exercises that I made. I searched the site for more information but have not found a solution for my problem. I apologize in advance for my bad english and if this is not the right place or the right way to ask this question because this is my first post in Stackoverflow.
Currently practicing HTML templates. Assuming that the code is correct, I'm not sure where I'm wrong. Loading code into the browser and Handlebars gives me an error: "Error: You must pass a string or Handlebars AST to Handlebars.compile. You passed undefined". I tried to debug and saw that when I tried to take a value from date object it gives back undefined. In previous exercise had a similar problem in which I tried to read JSON object and did not manage to parse it and returned again undefined. Can you help me, I am stuck on this problem for some time.
var data = {
animals: [{
name: 'Lion',
url: 'https://susanmcmovies.files.wordpress.com/2014/12/the-lion-king-wallpaper-the-lion-king-2-simbas-pride-4685023-1024-768.jpg'
}, {
name: 'Turtle',
url: 'http://www.enkivillage.com/s/upload/images/a231e4349b9e3f28c740d802d4565eaf.jpg'
}, {
name: 'Dog'
}, {
name: 'Cat',
url: 'http://i.imgur.com/Ruuef.jpg'
}, {
name: 'Dog Again'
}]
}
window.onload = function() {
var htmlTemplate = document.getElementsByClassName('container-template').innerHTML;
var template = Handlebars.compile(htmlTemplate);
for (let x of data.animals) {
if (x.hasOwnProperty('url')) { //x.url
x.hasUrl = true;
} else {
x.hasUrl = false;
}
}
document.getElementsByClassName('container').innerHTML = template(data);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Animals & Batman</title>
</head>
<body>
<div class="container">
</div>
<script class="container-template" type="text/x-handlebars-template">
<h1>Animals</h1>
{{#each animals}}
{{#if hasUrl}}
<li>
See a {{name}}
</li>
{{else}}
<li>
No link for {{name}}, here is Batman!
</li>
{{/if}}
{{/each}}
</script>
<script src="../handlebars-v4.0.5.js" charset="utf-8"></script>
<script src="../jquery-3.1.0.js" charset="utf-8"></script>
<script src="./main.js" charset="utf-8"></script>
</body>
</html>
document.getElementsByClassName returns an array of elements, not a single one - since multiple elements on a page can have the same class.
What you probably want is to use the id instead of class:
<script id="container-template" type="text/x-handlebars-template">
var htmlTemplate = document.getElementById('container-template').innerHTML;
I'm using QUnit for unit testing js and jquery.
My HTML looks like this:
<!DOCTYPE html>
<html>
<head>
<title>QUnit Test Suite</title>
<script src="../lib/jquery.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.16.0.css" type="text/css" media="screen">
<script type="text/javascript" src="http://code.jquery.com/qunit/qunit-1.16.0.js"></script>
<!--This is where I may have to add startPage.html--->
<script src="../login.js"></script>
<script src="../test/myTests.js"></script>
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
</body>
</html>
Currently, I'm adding login.js as shown and I'm getting references correctly to objects defined in login.js.
However, functions in login.js contains references to some dom elements defined in startPage.html which is located elsewhere.
So, if I say $('#login-btn'), it is throwing an error. Is there any way to fix this?
Can I
(a) refer to startPage.html to my qunit page given above?
(b) refer to or load startPage.html in the file where I'm running tests (myTests.js):
QUnit.test( "a test", function( assert ) {
assert.equal( 1, "1", "String '1' and number 1 have the same value" );//works
assert.equal( login.abc, "abc", "Abc" );//works with attributes
assert.equal(($("#userid").val()),'', 'Userid field is present');//fails
assert.equal( login.ValidUserId(), true, "ValidUserId" );//fails with functions
});
Does QUnit provide any method to load Html/php files so they'll be defined prior to testing. Like 'fixtures' in jasmine?
EDIT: Please also tell what to do in case I have startPage.php
There are a couple of ways you can do this. The simplest is just to use the built-in QUnit "fixtures" element. In your QUnit HTML file, simply add any HTML you want in the div with the id of qunit-fixture. Any HTML you put in there will be reset to what it was on load before each test (automatically).
<html>
...
<body>
<div id='qunit'></div>
<div id='qunit-fixture'>
<!-- everything in here is reset before each test -->
<form>
<input id='userid' type='text'>
<input id='login-btn' type='submit'>
</form>
</div>
</body>
</html>
Note that the HTML in the fixture doesn't really have to match what you have in production, but obviously you can do that. Really, you should just be adding the minimal necessary HTML so that you can minimize any side effects on your tests.
The second option is to actually pull in the HTML from that login page and delay the start of the QUnit tests until the HTML loading is complete:
<html>
<head>
...
<script type="text/javascript" src="http://code.jquery.com/qunit/qunit-1.16.0.js"></script>
<script>
// tell QUnit you're not ready to start right away...
QUnit.config.autostart = false;
$.ajax({
url: '/path/to/startPage.html',
dataType: 'html',
success: function(html) {
// find specific elements you want...
var elem = $(html).find(...);
$('#qunit-fixture').append(elem);
QUnit.start(); // ...tell QUnit you're ready to go
}
});
</script>
...
</head>
...
</html>
Another way to do this without using jquery is as follows
QUnit.config.autostart = false;
window.onload = function() {
var xhr = new XMLHttpRequest();
if (xhr) {
xhr.onloadend = function () {
if(xhr.status == 200) {
var txt = xhr.responseText;
var start = txt.indexOf('<body>')+6;
var end = txt.indexOf('</body>');;
var body_text = txt.substring(start, end);
var qunit_fixture_body = document.getElementById('qunit-fixture');
qunit_fixture_body.innerHTML = body_text;
}
QUnit.start();
}
xhr.open("GET", "index.html");
xhr.send();
} else {
QUnit.start(); //If getting the html file from server fails run tests and fail anyway
}
}
I'm using the following code to take images from a parse.com class and return them to the page inserted within a div.
At the moment I get a Uncaught TypeError: Object [object Object] has no method 'src'
and no images are being returned.
The images are stored in the class Gbadges in parse.com and as a string (URL) in the column.
I cannot find an complete match on SO or google to this issue. I presume its something to do with the image url?
Please note that this code is is based on backbone.js framework, which lets you ebed script tags into your html 5 code.
I've created a fiddle here http://jsfiddle.net/Dano007/cQgJG/
<!doctype html>
<head>
<meta charset="utf-8">
<title>My Parse App</title>
<meta name="description" content="My Parse App">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/styles.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.17.min.js"></script>
</head>
<body>
<div id="main">
<h1>You're ready to use Parse!</h1>
<p>Read the documentation and start building your JavaScript app:</p>
<ul>
<li>Parse JavaScript Guide</li>
<li>Parse JavaScript API Documentation</li>
</ul>
<div style="display:none" class="error">
Looks like there was a problem saving the test object. Make sure you've set your application ID and javascript key correctly in the call to <code>Parse.initialize</code> in this file.
</div>
<div style="display:none" class="success">
<p>We've also just created your first object using the following code:</p>
<code>
var TestObject = Parse.Object.extend("TestObject");<br/>
var testObject = new TestObject();<br/>
testObject.save({foo: "bar"});
</code>
</div>
</div>
<script type="text/javascript">
Parse.initialize("79tphN5KrDXdjJnAmehgBHgOjgE2dLGTvEPR9pEJ", "9lblofQNZlypAtveU4i4IzEpaOqtBgMcmuU1AE6Y");
var TestObject = Parse.Object.extend("TestObject");
var testObject = new TestObject();
testObject.save({foo: "bar"}, {
success: function(object) {
$(".success").show();
},
error: function(model, error) {
$(".error").show();
}
});
var GlobalBadges = Parse.Object.extend("GBadges");
var query = new Parse.Query(GlobalBadges);
query.exists("Global_Badge_Name");
query.find({
success: function(results) {
// If the query is successful, store each image URL in an array of image URL's
imageURLs = [];
for (var i = 0; i < results.length; i++) {
var object = results[i];
imageURLs.push(object.get('Global_Badge_Name'));
}
$('#Image01').src(imageURLs[0]); //first image
$('#Image02').src(imageURLs[1]); //second image
$('#Image03').src(imageURLs[2]); //third image
},
error: function(error) {
// If the query is unsuccessful, report any errors
alert("Error: " + error.code + " " + error.message);
}
});
</script>
<div >
<img id="Image01"/>
<img id="Image02"/>
<img id="Image03"/>
</div>
</body>
</html>
</body>
</html>
You need to use attr() to set the value of src attribute.
$('#Image01').attr('src',imageURLs[0]);
It is because the javascript is before the elements. Place the javascript below the elements (Image elements) and it should work fine.