I want to call a definition that is located in Python with a parameter, using AJAX. The web framework I'm using is Flask.
In my test.py
file:
def example(param):
In my JS file
$.ajax({
type: 'POST',
url: "test.py"
//pass param here?
});
I want to call a definition that is located in Python with a parameter, using AJAX. The web framework I'm using is Flask.
In my test.py
file:
def example(param):
In my JS file
$.ajax({
type: 'POST',
url: "test.py"
//pass param here?
});
$.ajax({
type: 'POST',
url: "test.py"
data: {
param: param
}
});
make sure to include your CSRF token. You can learn more about it here http://flask.pocoo.org/snippets/3/
you can add this to your js code.
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});