Function didn`t render_template Flask [duplicate] - javascript

I have an HTML page with a typical structure:
<html>
<head>
<script src="..." ></script>
<style>...</style>
</head>
<body>
content
</body>
<script>
var success_callback = function(data) {
// REPLACE PAGE CONTENT & STRUCTURE WITH "data"
}
ajax(url, params, success_callback);
</script>
</html>
Do you think it is possible ? I've already tried to give the html tag an id and doing $(id).replace(data); with no success.
Don't ask me why, but that is what I need (I'm working with a special "mashup builder" site... it is a long story).
EDIT : I forgot to say that scripts in the received content have to be executed, even external scripts included using <script src="...">.

The simplest way is to set the new HTML content using:
document.open();
document.write(newContent);
document.close();

try this with jQuery:
$('body').load( url,[data],[callback] );
Read more at docs.jquery.com / Ajax / load

Here's how to do it in Prototype: $(id).update(data)
And jQuery: $('#id').replaceWith(data)
But document.getElementById(id).innerHTML=data should work too.
EDIT: Prototype and jQuery automatically evaluate scripts for you.

You could try doing
document.getElementById(id).innerHTML = ajax_response

the simplest way is
$("body").html(data);

Can't you just try to replace the body content with the document.body handler?
if your page is this:
<html>
<body>
blablabla
<script type="text/javascript">
document.body.innerHTML="hi!";
</script>
</body>
</html>
Just use the document.body to replace the body.
This works for me. All the content of the BODY tag is replaced by the innerHTML you specify.
If you need to even change the html tag and all childs you should check out which tags of the 'document.' are capable of doing so.
An example with javascript scripting inside it:
<html>
<body>
blablabla
<script type="text/javascript">
var changeme = "<button onClick=\"document.bgColor = \'#000000\'\">click</button>";
document.body.innerHTML=changeme;
</script>
</body>
This way you can do javascript scripting inside the new content. Don't forget to escape all double and single quotes though, or it won't work. escaping in javascript can be done by traversing your code and putting a backslash in front of all singe and double quotes.
Bare in mind that server side scripting like php doesn't work this way. Since PHP is server-side scripting it has to be processed before a page is loaded. Javascript is a language which works on client-side and thus can not activate the re-processing of php code.

I'm assuming you are using jQuery or something similar. If you are using jQuery, then the following should work:
<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
</head>
<body>
content
</body>
<script type="text/javascript">
$("body").load(url);
</script>
</html>

Related

Using jquery in js file

Okay so all I am trying to do is make the jquery work in my javascript file which is linked to a html file. I created a totally new file for this to test it. The whole contents of the html file are:
<!DOCTYPE html>
<html>
<script src="C:\Users\Me\Desktop\Programming\jquery-1.12.4" type="text/javascript"></script>
<script src="check.js"></script>
<head> <h1>test</h1>
</head>
<body>
</body>
</html>
And the whole content of the js file is
$("h1").css("color", "red");
But when I open the html file in chrome the change I put in the js file with jquery doesn't show up (e.g the heading is not red). I just want to figure out how to make it so that it does.
EDIT:
Thanks for the help everybody, I was able to make it work :)
did you try this?
$(document).ready(function(){
$("h1").css("color", "red");
});
not sure but, does your browser access local files directly? im pretty sure that browser sandbox gonna reject that, maybe cors plugin on chrome?
EDIT:
try importing this instead...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
Move your <h1> tag to be in the <body>
Move your <script> tags to the <head>
Replace your code in your JS file with what imvain2 said, so
that the JS will load once your document is ready.
Make sure you are correctly referencing your jQuery script. You can even use this to test it out:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
Try to use jQuery CDN, this way you don't need to worry if jQuery loaded correctly or not.
$(document).ready(function() {
$("h1").css("color", "red");
});
<!DOCTYPE html>
<html>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="check.js"></script>
<head></head>
<body>
<h1>test</h1>
</body>
</html>
There are a couple issue as described in other posts. All your meta, script, css references, etc. should go int the <head> and never header tags. Also need to correctly reference your javascript files.
<head>
</head>
<body>
<header>
<h1>test</h1>
</header>
</body>
Example: JSFiddle
If you want to use jquery in .js file all you need to do is type: src=" ..." above code.

HTML Tidy fails on script tag in JavaScript string literal

I'm using HTML Tidy in PHP and it's producing unexpected results because of a <script> tag in a JavaScript string literal. Here's a sample input:
<html>
<script>
var t='<script><'+'/script>';
</script>
</html>
HTML Tidy's output:
<html>
<script>
//<![CDATA[
var t='<script><'+'/script>';
<\/script>
<\/html>
//]]>
</script>
</html>
It's interpreting </script></html> as part of the script. Then, it adds another </script></html> to close the open tags. I tried this on an online version of HTML Tidy (http://www.dirtymarkup.com/) and it's producing the same error.
How do I prevent this error from occurring in PHP?
After playing around with it a bit I discovered that one can use comment //'<\/script>' to confuse the algorithm in a way to prevent this bug from occurring:
<html>
<script>
var t='<script><'+'/script>'; //'<\/script>'
</script>
</html>
After clean-up:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<script>
var t='<script><'+'/script>'; //'<\/script>'
</script>
<title></title>
</head>
<body>
</body>
</html>
My guess is that as the clean-up algorithm looks through the codes and detects the string <script> twice, it looks for </script> immediately. And separting < with /script> makes the second </script> goes undetected, which is why it decided to add another </script> at the end of the codes and somehow also closed it with antoher </html>. (Poor design indeed!)
So I made a second assumption that there isn't an if-statement in the algorithm to determine if a </scirpt> is in a comment, and I was right! Having another string <\/script> as a javascript comment indeed makes the algorithm to think that there are two </script> in total.
There's no need for string concatenation to avoid the closing </script>. Simply escaping the / character is enough to "fool" the parsers in browsers and, it seems, HTML Tidy's parser as well:
<html>
<script>
var t='<script><\/script>';
</script>
</html>
Try to make the script tag not a full word but a string concatenation
<html>
<script>
var t='<scr'+'ipt><'+'/script>';
</script>
</html>
Resulting cleaned code
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<script>
var t='<scr'+'ipt><'+'/script>';
</script>
<title></title>
</head>
<body>
</body>
</html>
This is probably a better practice to create a script tag like this:
(this should also solve your tidy issues)
<script>
script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://myserver.com/file.js';
document.getElementsByTagName('head')[0].appendChild(script);
</script>
One way is to make it so tidy doesn't detect the script tag. The "cleanest" way I could come up with is to escape a character in the tag.
<html>
<script>
var t='<\script><'+'/script>';
</script>
</html>
so you could even do this, without having to break the string up as above:
var t='<\script></\script>';
That just works as expected
<html>
<script>
var t='<'+'script><'+'/script>';
</script>
</html>
By the way, string concatenation is not best way to create dynamically HTML to insert in page, look for document.createElement or even templates engines (handlebars.js is my favourite)

Can't import javascript code with innerHTML

I've built a webpage that is basically a main-page with a div that is filled with different pages by using AJAX. This basically works by loading pages into a div by using innerHTML. One problem I ran into was when a page with javascript is loaded into that div all of the other code runs fine; just the javascript doesnt work.
Main-page(index.php):
<html>
<head>
<script type="text/java">
////bunch of functions////
////Ends up that page_request on this instance is 'graph.php'////
document.getElementById('mydiv').innerHTML=page_request.responseText
</script>
</head>
<body>
<div id="mydiv"><div>
</body>
</html>
Child-page(loaded in div(graph.php)):
<html>
<head>
<link rel="stylesheet" href="mystyle.css" type="text/css" media="screen" />
<script src="other_stuff.js"></script>
</head>
<body>
<script>
///bunch of script////
</script>
</body>
</html>
Now when loading the page itself (opening graph.php) I notice that everything works fine; it is just when I import graph.php to index.php through innerHTML into my div it does not work (no errors just nothing is shown). I have read through many other posts and guides and did not come up with any distictive solution; thinks I have seen were:
Put eval() around my code [I saw on a guide that this could lead
to malicious user attacks].
Create the scripts on the main page then just import the data using:
document.createElement() and .parentNode.insertBefore()
Create a listener and call the functions when I open graph.php
And this good example
Even though I am not 100% sure how this example could work because I have php populate information for the javascript to collect and then make my graph on graph.php; so if I put that function into index.php the php will already be loaded so I would have to refresh the page or call them to update information somehow. Just for some context I am ok at php but I am new and struggle with javascript so I do not know what solution would fit my situation or work the best. Any tips/examples would be greatly appreciated, thank you for your time.
From you code snippets it seems you're looking to embed complete pages within the main page. If that's the case, a more straightforward approach would be to use an iframe element instead.
For example:
...
<div id="main-page-container">
<iframe src="some-path/graph.php" scrolling="no" frameborder="no"></iframe>
</div>
...
See reference and usage example.
I would suggest using jQuery's .load() function for this.
Take a look here: jQuery API
Older browsers such as IE8 and below don't allow you insert a string that contains javascript and execute it, in any form.
Take for instance:
function addScriptText(js_code) {
var element = document.createElement("script");
element.innerHTML = js_code;
document.head.appendChild(element);
}
will not work in IE8 and below.
You must use eval to accomplish this:
function addScriptText(js_code) {
window.eval.call(window, js_code);
}
Otherwise you need to dynamically request an external js file such as:
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "externalScript.js";
document.getElementsByTagName("head")[0].appendChild(script);
Note: The page you are loading (page2.html in this example) must be on the same domain as the page that is loading it (page1.html in this example)
Working solution with jQuery:
Page 1:
<!DOCTYPE html>
<html>
<head>
<title>Page 1</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#page2").load("page2.html");
});
</script>
</head>
<body>
<h1>Page 1 Header</h1>
<div id="page2">
</div>
</body>
</html>
Page 2:
<h2>Page 2 Header</h2>
<script type="text/javascript">
alert("Page 2 loaded and javascript executed!");
</script>

How to replace Current script tag with HTML contents generated by the same script

I want to replace the current script tag with the HTML contents generated by the same script.
That is, my Page is
<html>
<body>
<div>
<script src="myfile1.js"></script>
</div>
<div>
<script src="myfile1.js"></script>
</div>
</body>
</html>
Inside each .js file corresponding html contents are generated. I want to put the contents as the innerHTML of the parent div. But can't set id for the parent div because the page is not static. So the current script tag must be replaced with the HTML content. How can I do this?
For each script tag src is the same. So can't identify with src. These scripts displays
some images with text randomly. Scripts are the same but displays different contents in divs on loading
Please help me
try inside of myfile1.js:
var scripts = document.getElementsByTagName( "script" );
for ( var i = 0; i < scripts.length; ++ i )
{
if ( scripts[i].src == "myfile1.js" )
{
scripts[i].parentNode.innerHTML = "new content";
}
}
This is a great question for those trying to implement a JSONP widget. The objective is to give the user the shortest possible amount of code.
The user prefers:
<script type="text/javscript" src="widget.js"></script>
Over:
<script type="text/javscript" src="widget.js"></script>
<div id="widget"></div>
Here's an example of how to achieve the first snippet:
TOP OF DOCUMENT<br />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
// inside of widget.js
document.write('<div id="widget"></div>');
$(document).ready(function() {
$.getJSON('http://test.com?remote_call=1', function(data) {
$('#widget').html(data);
});
});
<br />BOTTOM OF DOCUMENT
Have a look at: http://alexmarandon.com/articles/web_widget_jquery/ for the correct way to include a library inside of a script.
document.currentScript has been available since 2011 on Firefox and 2013 on Chrome.
document.currentScript documentation at MDN
<!DOCTYPE html>
<meta charset="UTF-8">
<title>currentScript test</title>
<h1>Test Begin</h1>
<script>
document.currentScript.outerHTML = "blah blah";
</script>
<h1>Test End</h1>
Unfortunately a running JavaScript file is not aware of where it is running. If you use document.write() in the script, the write function will take place wherever the script runs, which would be one way to accomplish what you want, but without replacing the contents or being able to perform any actions on the enclosing DIV.
I can't really envisage a situation where you'd have such stringent restrictions on building a page - surely if the page is dynamic you could generate identifiers for your DIV elements, or load content in a more traditional manner?
Why not use Smarty?
http://www.smarty.net/
You can use javascript in Smarty templates, or just use built-in functions.
Just take a look at http://www.smarty.net/crash_course
poof -- old answer gone.
Based on your last edit, here's what you want to do:
<html>
<head>
<!-- I recommend getting this from Google Ajax Libraries
You don't need this, but it makes my answer way shorter -->
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function getRandomContent(){
// I expect this is the contents of your current script file.
// just package it into a function.
var rnd = Math.random();
return "[SomeHtml]";
}
$('.random').each(idx, el){
$(this).html(getRandomHtmlContent());
});
});
</script>
</head>
<body>
<div class="random">
</div>
<div class="random">
</div>
</body>
</html>
If you don't mind the script tag remaining in place you can use something as simple as document.write().
myfile1.js:
document.write("<p>some html generated inline by script</p>");
It will do exactly what you need.

Missing } in XML Expression

I am trying to change our site to load a Header through jquery using the .load() function but to do so I need to set the Title of the page.
From another StackFlow question it was suggested to do something as simple as
$(document).ready(function() {
document.title ='Name Changed to Protect the Innocent';
});
When i do this I get the firebug error
Missing } in XML Expression for that line in the script
I am sure there is probably an easy solution but it is certainly escaping me.
I've just tested this out here, please see if you have created your html document in the same way. Code as below.
<html>
<head>
<title>Old Title</title>
<script type="text/javascript" src="jquery-1.4.2.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
document.title ='Name Changed to Protect the Innocent';
});
</script>
</body>
</html>
I found what the problem was. This script was in the middle of another script block which was causing the error.
Thanks for all the help.

Categories