Flask send_file as attachment not working - html

I'm using flask's send_file method to try and make the browser download a .txt file. Problem is the browser does not download anything.
Here's my python function:
#app.route('/download_zip', methods=['POST'])
def download_zip():
file_name = 'test.txt'
return flask.send_file(file_name, as_attachment=True, mimetype='text/plain')
Here's my jQuery function that triggers the POST request:
function batchDownload() {
$.post('/download_zip', {
file_name: 'temp.zip'
}).done(function(data) {
alert(data);
}).fail(function() {
alert('Error. Could not download files :(');
});
}
Funny thing is the alert(data) in the .done(...) callback displays the file's content to the browser. So the browser is receiving the file content but just not downloading it.
Any ideas?
Thanks in advance!
EDIT
Added a form to the page:
<form id="download"></form>
And added this to the .done(...) callback:
$form = $('#download');
$form.submit();
I'm guessing I need to somehow link the data (file) returned by the server response to the POST request?

This is not a flask related question.
It's how browsers and javascript works.
You're downloading the file in Ajax so the result is passed to your Ajax callback.
You want instead to make the browser download data in his usual way.
To do so you must use a form and call the .submit() method on it.
Just create the form in the page with hidden fields and submit it in the javascript function. It should do the trick.

Related

Using Django, how can submit a form silently and not return a HTTP response in my views as to not reload a web page when a view function is called

How can I call my view function from a button click and have it return something that would result in my web page not reloading? It seems that I must return an HTTP request in some way in views.py or I get an error. "I do not wish to stop the form submission". I would prefer not to use Ajax at this moment.
I have a page with a long list of objects from my database that users can input quantities and click a button which sends the form data to a cart object. In doing this, the corresponding view function is triggered and returns some sort of HTTP Response which results in the page loading in some way. I would like it so that absolutely nothing happens when a button is clicked, other than the form data being submitted. Not even a redirect to the same page. This is because I don't want the user to lose there place on the page and have to scroll through a list of objects to find where they were.
views
def add_to_cart(request, product_id):
return HttpResponse('')
url path
path('cart/add/<product_id>', home_views.add_to_cart, name='add_to_cart'),
Quote
<form action="{% url 'add_to_cart' product.id %}" method="post">{% csrf_token %}</form>
If you really don't wish to use AJAX, reload the page, or have any of the changes the POST does reflect in your page, you can add a hidden <iframe> that you set as the form's target.
<iframe name="submit-frame" style="display: none"></iframe>
...
<form target="submit-frame">...</form>
This effect is not maked by your Django Backed,you can post your form data by ajax request to make this result
You can try something like calling post() on button click like this:
function post() {
$.ajax({
type : 'POST',
url : 'post/', //whatever relative url you want to use
data : { msgbox : $('#input-id').val() }, //the input id of what you are submitting
success : function(json){ //do stuff if post is successful
$('#chat-msg').val(''); //can set the to blank
}
});
}
Just add this to your javascript or in a script tag, but you will need to add JQuery as mentioned below:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

How to communicate from my Controller to my HTML with sprint bootstrap?

I am sending a <form> with an input type="file" and a submit button via http and now it seems to work fine. My Controller gets the file and I can check the file e.g. for correctness.
After I checked if the file is correct, I want to interact with my Front-End, I want to display a String in a label and maybe interact with drop-down-menus etc.
In the future I want to be able to display the data-results my program is creating.
How do I communicate from my controller (I guess via HTTP) with my HTML code?
One way is make an ajax request.
You make a request in background to your server, when he responds you can make everything with JavaScript.
Jquery implement methods to use ajax request.
You can do it dynamically with Ajax, but its quite complicated:
Sending file together with form data via ajax post
$.ajax({
type: 'POST',
url: 'your_controller_address',
Ajax target would be your controller, and you'd need to make your controller return for example json data and process it in:
success: function(response)
{
if(response.success == true) {
//yourcode to show notification
}
}
Controller:
#RequestMapping(value="/your_controller_address", method=RequestMethod.POST)
#ResponseBody
public String some_method(#ModelAttribute("form_model") Form_model_type form_model) {
//do your stuff with model here
return "{\"success\":\"true\"}";
}
The other way, less efficient is to send form to another controller (<form action="/your_controller_address") which process your data and shows you notification, but it requires to reload whole page.

HTML Forms post redirect

I've got an HTML form that I'm posting to a url successfully. However, I need to have the page be redirected after I've posted the form. I'm not able to use ajax because CORS is not enabled. When I post to the url I'm getting a success message, and a redirect link in json format. This seems much easier than it's proving to be.
What I know is, when I post to the original url, a cookie is created, and when I go to the url that the page is returning, I am an authenticated user. So, it seems that I need to capture that cookie, and then redirect, but I could be off base.
This can be achieved using custom scripting.
The script waits for the input button to be clicked and sets up a listener that checks to see if the div that holds the confirmation text is visible and then sends the user to the destination page.
Add this to the code injection point for the page that holds the form:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
var eventposted=0;
$(document).ready(function(){
$('input.button').click(function() {
window.setInterval(foo, 100);
});
});
function foo(){
if(($(".form-submission-text").is(':visible')) && (eventposted==0)){
window.location = "http://www.something.com/destinationpage";
eventposted=1;
}
}
</script>

JSON response from URL

Hey I'm trying to retrieve data from a json file I have hosted on my server but it's not working, I'm not sure what is wrong as I'm not the most well versed in this topic. Any tips are appreciated!
$(document).ready(function () {
$("#button").click(function () {
$.getJSON({
type: "POST",
url: "some URL will go here",
success: function (result) {
$("#div1").append(result);
}
});
});
});
heres the fiddle as well: http://jsfiddle.net/ahuston12/E5SzH/
Open a modern browser like Firefox or chrome and open the developer tools. Navigate to the page that contains the above code and monitor the "network" tab to see the related http request triggered via ajax. You can then see the request + response including header, body and return codes. This should help to figure out the problem.
You should show us what's going on the server side.
It doesn't seems to be problems on this jquery code so i guess it's from server.
You can check the response value to see the problem :
on chrome ctrl+j -> network. You'll see your request, click on it to see details like the server's response.
If you have FireBug installed in your Mozilla Firefox open it, in that you can see Net Tab . If you click that you can able to see what kind of response you are getting. I ahve attached the Image For your reference. And for getting a JSON result use "result.d".
The url that you are using doesn't return a json response, it returns a javascript file that charge a json result into a variable, because of that you can't get the result.. if you try with other site that returns information in json format like this you are going to get the data:
$.getJSON("http://headers.jsontest.com/", function (result) {
console.log(result);
}
);

Mootools Request to change javascript code?

So I am planning on dynamically changing a page's content by fetching it from another page.
To do so, I used Mootools' Request class:
var tabContent = new Request({
url: 'foo/bar/baz.php',
onSuccess: function(data) {
$('tab_container').innerHTML = data;
}
}).send();
In any case, the HTML is fetched fine, and returns without a hitch. However, I'd like to add some events to THOSE fetched elements (Fx.slide, to be precise), and that requires some js to be included in the requested file.
Upon inspection of the returned data, the javascript is intact. However, it does not show up in the final product. That is, somewhere in between having received the data, and rendering the data (via the innerHTML bit) it seems as though the javascript has been excised out for some reason.
Hm.
add evalScripts: true to the Request options, then include the script in a simple <script></script> block at the bottom of the response.