I want to pass a variable using Ajax from a JS function to a python function in my Django project. I am able to call the python function. Using the ajax method, I know this because the print function in the python function runs. However how to I pass my variable through this ajax call? I just want to pass the local variable so it can be printed by the python function.
JS
function calling (){
var local = 25
$.ajax({
type:'GET',
url:'printsome/',
success: function(response){
console.log('success');
console.log(local);
},
error: function (response){
console.log('error');
}
});
}
python
def print_some(request):
from django.http import JsonResponse
print('this python function was called')
return JsonResponse({})
CodePudding user response:
For example, you can pass the variable as a queryparameter:
function calling (){
var local = 25
$.ajax({
type:'GET',
url:`printsome/?variable=${local}`, // <- Add the queryparameter here
success: function(response){
console.log('success');
console.log(local);
},
error: function (response){
console.log('error');
}
});
In django you can access the queryparameter like the following:
from django.http import JsonResponse
def print_some(request, ):
variable = request.GET.get('variable', 'default')
print('Variable:', variable)
return JsonResponse({})
Read more about it here: HttpRequest.GET