Created On: May 31, 2021, Last Updated On: August 30, 2023
By Ozzie Ghani3 new
html file
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-globe"></i></span>
</div>
<input placeholder="{{ session['domain'] }}" type="text" class="form-control" id="set_domain_input">
<div class="input-group-append">
<button class="btn btn-success" id="set_domain_btn">Set</button>
</div>
</div>
Preview
You will need to set following
<script type=text/javascript>
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
</script>
also
<meta name="csrf-token" content="{{ csrf_token() }}">
var csrftoken = $('meta[name=csrf-token]').attr('content');
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", csrftoken)
}
}
});
Alternatively, you can set
<meta name="csrf-token" content="{{ csrf_token() }}">
var csrf_token = "{{ csrf_token() }}";
$.ajax({
type: 'POST',
url: '/login',
headers: {
"X-CSRFToken": csrf_token,
}
data: {
...
Sample Ajax
$(document).ready(function() {
$(document).on('click', '#set_domain_btn', function() {
var csrf_token = "{{ csrf_token() }}";
var domain = $('#set_domain_input').val();
data = {"domain": domain};
$.ajax({
url: "{{ url_for('toor.setdomain') }}",
contentType: 'application/json;charset=UTF-8',
data: JSON.stringify(data, null, '\t'),
headers: {
"X-CSRFToken": csrf_token,
},
type: 'POST',
dataType: 'json',
success: function(response) {
console.log(response);
window.location.reload();
},
error: function(error) {
console.log(error);
}
});
});
});
python
@app.route('/set', methods=['GET', 'POST'])
def setdomain():
if request.method == "POST":
r = request.get_json()
# r = request.get_json(force=True)
domain = r['domain']
print(domain)
return jsonify({"domain": domain})
How to manually add csrf token in html form
<form id="regForm" action="/login" method="POST" role="post">
<input id="csrf_token" name="csrf_token" type="hidden" value="{{ csrf_token }}">
<input type="submit" value="Submit" />
</form>