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.
Related
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>
I'm developing a ASP.NET Core web application where I'm using DataAnnotations to decorate my view model with validation attributes. When I open a detail page with my inputs, I see that Core added the HTML5 validation attributes to the rendered HTML (i.e. data-val="true").
However, I wrote custom client-side code when the user clicks on the Save button like this:
$(document).on("click", "#SaveAsset", function (event) {
event.preventDefault();
Asset.Save();
});
I also have a Save function defined like this:
window.Asset.Save = function () {
var postData = {
'Id': $("#Id").val(),
'SerialNumber': $("#SerialNumber").val(),
'PartNumber': $("#PartNumber").val(),
'assetTypeId': $("#AssetTypeId").val()
};
$.post('/Asset/SaveAsset', postData);
}
I need to validate on the client side first before calling $.post but I'm confused about how to do it. Microsoft shows that the unobtrusive javascript works automatically when you use it with forms. But I'm not using the HTML form element to submit my page. So how can I trigger the HTML5 validation attributes?
I added the links to jquery.validate.js and jquery.validate.unobtrusive.js. Right now, if I click the Save button the data is sent to the server and the controller checks the ModelState. But it shouldn't even be sending anything to the server. The client should stop the validation.
Should I even stop doing it this way? For example, creating my postData JSON object by getting the val() of each input.
Should I use the form element? I stopped using it because my page has hundreds of inputs so I was worried I would have problems. This way, I have control over each input.
Use a javascript solution like jQuery Validation Plugin to validate data before sending to the server. Otherwise, send the data to the server, and return a the errors with a bad request if validation fails.
Eg.
Return BadRequest(string[]{"Name is required", "Id must me a number"});
then capture the errors and shoe to the user
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.
First let me set the situation.
I am writing a simple client html page and a simple server side program.
In detail, the page has a submit button to POST some data to the server program.
The problem is that any time I test the page to push the submit button ,the browser displays the new page which displays only the return message my server program returned.
How can I modify the html or the server side program so that the browser keeps the page unchanged before after the submit button is pushed.
I know an easiest way ; letting the sever program returns the same string as the client html page.
Thank you in advance.
In a regular form submission, your page will be whatever the server sends back. The form's action might be the same page, and then your server-side code can read the value of any input fields, and set the values in the response back to what they were in the request. This should result in the page looking the same as it did before the submit button was pressed. However, the page has "changed" in the sense that it was reloaded.
Alternatively, your form can make an Ajax request, which means that you'd need to use Javascript to intercept and stop the form submission, and then use additional coding to send the Ajax request, and then receive and process the response.
What you want is probably a postback:
http://en.wikipedia.org/wiki/Postback
1.) AJAX
You could use JavaScript and AJAX to POST the data.
2.) IFrame (not recommended)
You could also create a hidden IFrame and set the target attribute of the form to it.
What you want to do doesn't seem to be very clear.
If you want to submit your POST data without loading a new web page, you can use Ajax. It may be simple to do it in jQuery, and even simpler if you serialize your form data.
$('form').submit(function() {
$.post('your-post-url',$(this).serialize(),function(data) {
alert('Data posted!');
});
return false;
});
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.