jQuery fileDownload plugin doesn't show popup window, how to fix this? - javascript

I'm using jQuery for my frontend part of an application (backend runs on Flask) and I needed a plugin for displaying some kind of information to user while he's waiting for a file to be served to him (and I also need to work with older versions of IE, which is why I've decided to use this plugin).
Unfortunately I haven't been able to do anything with it due to some weird JS errors I'm getting (screens and my example code below).
Example server-side code:
from flask import Flask, send_file, render_template
import os
from time import sleep
app = Flask(__name__)
#app.route('/', methods=['GET'])
def mainRoute():
return render_template('index.html')
#app.route('/filesfordl/file.txt', methods=['GET'])
def fileRoute():
sleep(5) # time for window to appear
fileResponse = send_file(os.path.join(os.getcwd(), 'filesfordl/file.txt'), as_attachment=True, attachment_filename='file.txt')
fileResponse.set_cookie('fileDownload', 'true')
return fileResponse
if __name__ == '__main__':
app.run('0.0.0.0', '5000')
My index.html:
<html>
<head>
<script type="text/javascript" src="{{ url_for('static', filename='js/jquery-3.3.1.min.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/jquery.fileDownload.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/script.js') }}"></script>
</head>
<body>
Get file!
</body>
</html>
And finally JS part:
/*$.fileDownload('/filesfordl/file.txt', {
successCallback: function (url) {
alert('You just got a file download dialog or ribbon for this URL :' + url);
},
failCallback: function (html, url) {
alert('Your file download just failed for this URL:' + url + '\r\n' +
'Here was the resulting error HTML: \r\n' + html
);
}
});
*/
$(function() {
$(document).on("click", "a.fileDownloadSimpleRichExperience", function() {
$.fileDownload($(this).attr('href'), {
preparingMessageHtml: "We are preparing your report, please wait...",
failMessageHtml: "There was a problem generating your report, please try again."
});
return false; //this is critical to stop the click event which will trigger a normal file download!
});
});
^^ in this part if I uncomment the upper code, it always triggers failCallback after entering index.html even if I don't click on the link.
After clicking the hyperlink i get this error message (can't post images directly yet):
this
Which ultimately leads to this line in the plugin's code.
this
EDIT:
I've added some debugging prints on top of the problematic line:
console.log($("<div>").html(settings.preparingMessageHtml).dialog);
console.log($("<div>").html(settings.preparingMessageHtml));
And output I'm getting after that is.
Any ideas on what I'm doing wrong?

Okay, nevermind, I simply forgot to include jQuery UI files which is the sole reason of my issues, topic can be closed.

Related

Python flask script not executing as expected

I'm trying to execute a function based on a button click via javascript.
I've copied a tutorial on how to do this, but nothing happens.
I've added a break point in the function that should be executed (background_process_test), but the program never executes the function.
What am I missing to get this simple tutorial working?
I'm running on a local machine with waitress.
python code:
from flask import Flask, render_template, request
from flask import jsonify
from waitress import serve
app = Flask(__name__)
#rendering the HTML page which has the button
#app.route('/json')
def json():
return render_template('json.html')
#background process happening without any refreshing
#app.route('/background_process_test')
def background_process_test():
print ("Hello")
return ("nothing")
if __name__ == "__main__":
app.debug = True
serve(app, host='0.0.0.0', port=8080) #WAITRESS!
html code:
<!DOCTYPE html>
<html lang="en">
<head>
<!--<script src="/jquery/jquery-3.6.0.min.js"></script>-->
<script src="{{url_for('static', filename='jquery-3.6.0.min.js')}}"></script>
<script type=text/javascript>
(function() {
('a#test').on('click', function(e) {
e.preventDefault()
$.getJSON('/background_process_test', function(data) {
//do nothing
})
return false;
})
})
</script>
</head>
<body>
<div class='container'>
<h3>Test</h3>
<form>
<a href=# id=test><button class='btn btn-default'>Test</button></a>
</form>
</div>
</body>
</html>
Update:
Network tab
i somehow deleted the '$' sign. It was giving an error due to spacing in visual studio. Setting the spacing right, solved the issue. Many thanks for pointing me in the right direction.
There is a typo in the following code:
('a#test').on('click', function(e) {
...
})
Specifically, your attempt to use jquery get the list of elements that match 'a#test'. The code should be:
$('a#test').on('click', function(e) {
...
})

Why does my jQuery work inline but not externally?

I've been trying to learn how to implement AJAX and so far I've been tinkering with this jQuery example.
The code is located at static/js/form.js
(function ($, window, document) {
/* globals window, jQuery, document, console */
// enable this return statement to disable Ajax submission
// return;
$(document).ready(function () {
var myForm = $('#myForm');
myForm.on('submit', function (e) {
e.preventDefault();
var data = myForm.serialize();
$.post('/my-ajax-endpoint', data, function (result) {
if (result.success) {
alert(result.message);
} else {
alert('Error: ' + result.message);
}
console.log(result);
});
})
});
}(jQuery, window, document))
My html works when I have the above inline like this:
<html lang="en">
<head>
<title>Flask-WTF + Ajax Example </title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
{% block content %}{% endblock %}
<script type="text/javascript">
(function ($, window, document) {
/* globals window, jQuery, document, console */
// enable this return statement to disable Ajax submission
// return;
$(document).ready(function () {
var myForm = $('#myForm');
myForm.on('submit', function (e) {
e.preventDefault();
var data = myForm.serialize();
$.post('/my-ajax-endpoint', data, function (result) {
if (result.success) {
alert(result.message);
} else {
alert('Error: ' + result.message);
}
console.log(result);
});
})
});
}(jQuery, window, document))
</script>
</body>
</html>
But when I try to reference it as an external file like this:
<head>
<title>Flask-WTF + Ajax Example </title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type=text/javascript src="{{url_for('static', filename='js/form.js') }}"></script>
</head>
It doesn't seem to do anything.
I've also tried to put it just before </body> tag and still no go.
I don't have any working knowledge of JavaScript or jQuery, so if it's something simple then I apologize in advance. I am learning Flask and I wanted to try submitting form data without refreshing and it led me to down this rabbit hole.
EDIT: form.js shows up in console under sources but it's completely blank?
I'm the author of the Flask Ajax Example project that you're working with. I've added a new branch that moves the JS into a separate file that's now inside of a static directory: https://github.com/YellowSharkMT/flask-ajax-example/tree/example-with-static-js-file
I can't say for certain what the issue may have been - the url_for function that you were using in your template above should have done the trick. In my update, I simply added this line to the home.html template:
<script src="{{ url_for('static', filename='js/form.js') }}"></script>
And that's obviously nearly the same thing that you had above. One thing I'll add about Flask is that my example did NOT have debug mode enabled, and I've now enabled that in a separate commit. It makes development a bit easier by adding features like auto-reloading (of the python server) and less-aggressive caching. Go ahead and check that branch out, and let me know if you have any issues - good luck!

Calling function in HTML, from external .js file?

I am trying to call a function I've declared in my .js file, in my HTML document.
js/newsalerts.js
function unescapeHTML(html) {
//https://stackoverflow.com/a/2989105/4650297
var div = document.createElement("DIV");
div.innerHTML = html;
return ("innerText" in div) ? div.innerText : div.textContent; // IE | FF
}
index.html (using Flask)
<html>
<head>
<script type="text/javascript" src="{{ url_for('static', filename='js/newsalerts.js') }}"></script>
<script>
queries = "{{ search_terms }}";
console.log(unescapeHTML(queries));
</script>
...
I'm trying to get the unescapeHTML function to run on my queriesvariable, but keep getting the error that
unescapeHTML is not defined
I've also tried console.log(newsalerts.unescapeHTML(queries)), same error.
Unfortunately (?) the solution to this was not a programming one. Thanks to the folks commenting on my OP, I was able to confirm that my .js file was indeed loading correctly, and the code was correct.
...except looking through the code, my unescapeHTML function was missing -- but it was in my .js file!
The problem was when I restarted the Flask server, and refreshed my browser, it must have kept the js file from the cache. Once I did a hard refresh, the full correct js file loaded and it works as expected.
So, don't forget to "hard refresh" the page if you change any of the underlying code.

django tinymce javascript not loading on non-admin pages

Im trying to implement TinyMCE on Django, i have successfully implement it on admin page using settings like this :
admin.py:
class TinyMCEAdmin(admin.ModelAdmin):
class Media:
js = ('/media/js/tiny_mce/tiny_mce.js', '/media/js/tiny_mce/textareas.js',)
settings.py :
TINYMCE_JS_ROOT = '/media/js/tiny_mce/'
TINYMCE_JS_URL = '/media/js/tiny_mce/tiny_mce.js'
then when i try to implement it on my form(non-admin) :
forms.py:
from tinymce.widgets import TinyMCE
class Foo(forms.Form):
title = forms.CharField(max_length = 100)
content = forms.CharField(widget = TinyMCE())
When i see the result, it just showing plain html textarea, then i hit "F12" on Chrome, then it says : 'Uncaught reference error: tinyMCE is not defined'.
How do i fix that error? thx guys
Looking at the documentation, if you are using TinyMCE in your form outside of the admin, you need to tell it to include the JS/CSS required to render TinyMCE manually. So in your base template (or somewhere similar) you need to add:
<head>
...
{{ form.media }}
</head>
or you could simply manually load the js:
<head>
<script src="{{ MEDIA_URL }}js/tiny_mce/tiny_mce.js"></script>
<script src="{{ MEDIA_URL }}js/tiny_mce/textareas.js"></script>
</head>
but the former is probably easier
Looks like the file tiny_mce.js has not been loaded in this case.

jQuery $.load() functioning on personal webserver, but not production webserver

EDIT: I have discovered that this is a 405 error. So there is something going on with the webserver and handling POST methods.
I am having a strange occurrence. I have identical javascript code on both my test environment and production environment.
The test environment functions, and the production does not. Here is my identical code.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jquerytools.org/1.1.2/jquery.tools.min.js"></script>
<script type="text/javascript" src="./js/jquery.scrollTo-min.js"></script>
</head>
<body>
<div class="content" id="content">
<a id="changeText" href="test.html">Change</a>
</div>
<script>
$(document).ready(function() {
$("#changeText").live('click', function(){
var url = $(this).attr("href");
$("#content").load(url, {var1:Math.random()*99999},function(){
alert(url + " loaded");
});
$.scrollTo("0%", 400);
return false;
});
});
</script>
</body>
</html>
Both environments report that
alert(url + " loaded");
is happening. But only my test environment actually displays the change.
The production webserver has "test.html" available in the correct location.
Are you sure the scrollTo script is being included on the production server ( or am I misinterpreting what you mean by change ) ? Perhaps try a root relative path instead of './js'? I would check Firebug's script tab to ensure it is being included.
405 errors mean that the URL you're sending to isn't expecting you to send the data in that manner. For example, if you're sending a POST request to a URL that's only designed to handle a GET request, you'll get this error.
My guess is whatever server you're running on is set up to not allow POST data to be sent to a page with a .html extension, causing the error you're seeing. Try changing the extension to a .php, .aspx, etc, and see if that helps.

Categories

Resources