Reputation: 117
I'm trying to pass the values of the form and the values of the from
and till
variables to the Python. But it turns out to transfer or values of the form or value of variables.
If I post only var a = $('#form').serialize();
then in the python I can freely obtain the value by applying form.projects.data
If I post var a = $('#form').serialize();
and variables from
and till
that in a python a variable is displayed in the following form: projects=1
and this leads to additional processing.
{% set d_from, d_till = from_till %}
{% block module_scripts %}
{{ super() }}
<script>
var from = '{{ d_from.strftime("%m/%d/%Y") }}';
var till = '{{ d_till.strftime("%m/%d/%Y") }}';
$(function my() {
$("#reservation").daterangepicker({
"locale": {
"format": "DD/MM/YYYY"
},
"opens": "right",
"showDropdowns": true,
"showWeekNumbers": true
}, function (start, end, label) {
from= start.format('MM/DD/YYYY');
till = end.format('MM/DD/YYYY');
});
});
$( "#go" ).click(function() {
var a = $('#form').serialize();
$.post(
'{{ url_for("reporting_backoffice.download_report") }}', {
a:a,
d_from: from,
d_till: till
}
);
});
</script>
{% endblock %}
{% block report_block_content %}
<form id="form">
<div class="form-group">
<div class="input-group">
<div class="input-group-addon"><i class="fa fa-calendar"></i></div>
<input type="text" class="form-control pull-right" id="reservation"
value="{{ d_from.strftime("%m/%d/%Y") }} - {{ d_till.strftime("%m/%d/%Y") }}">
</div>
</div>
<div class="row">
<div class="col-lg-6">
{{ wtf.form_field(form.projects, class="form-control select2") }}
<button class="btn btn-primary" id="go">{{ _("Download report") }}</button>
</div>
</div>
</form>
Please tell me, maybe there is a more correct and simple way to POST
data to the Python?
Upvotes: 0
Views: 2381
Reputation: 171679
Could manually add the additional items as string by using $.param()
to convert the times object
var formData = $('#form').serialize(),
times = { d_from: from, d_till: till },
postDataString = formData + '&' + $.param(times);
$.post('{{ url_for("reporting_backoffice.download_report") }}', postDataString );
Demo:
var formData = $('#myForm').serialize(),
times = { d_from: 'xxxx', d_till: 'yyyy' },
postDataString = formData + '&' + $.param(times);
console.log(postDataString)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input name="AAA" value="a">
<input name="BBB" value="b">
</form>
Upvotes: 1
Reputation: 884
$(function() {
$("#form").on("submit", function() {
var $this = $(this);
$.ajax({
url: '{{ url_for("reporting_backoffice.download_report") }}',
data: $this.serialize(),
method: "POST",
success: function(data) {
//Here if u have to do something with the response
}
});
})
});
Now with python you have variables in query string object.
PS: if you don't set attribute "name" on form inputs, $(this).serialize() is useless and no variable is passed to python.
Upvotes: 1