I've been trying to get a POST to my Django views with the final goal to send a 'selected' input (from a clicked #id) and have Django send a response which I can dynamicly show. Using GET I'm able to recieve a response but the POST is giving me problems (I could go for GET but at this time I just want to understand why I'm messing up POST...;))
I have used several guides by now but most are about forms and, to be honest, I have trouble following the documentation (I have little to no background in programming).
Could someone point me in the right direction?
My HTML ('numberinput' is a placeholder for now):
<script>
$("#test").on(click(function () {
numberinput = 8;
$.ajax({
type: 'POST',
url: '{% url "rungenerator" %}',
data: {'numberinput': numberinput},
dataType: 'json',
success: function (inputtype) {
alert(inputtype)
}
})
}))
</script>
<div>
<form method="POST">
{% csrf_token %}
<button type="submit" id="test">Buzzzz Ping</button>
</form>
</div>
Views:
def rungenerator(request):
inputtype = "Please make a selection"
if request.method == 'POST':
inputtype = request.POST['numberinput',None]
return JsonResponse(inputtype)
URLS:
url(r'^ajax/rungenerator/$', views.rungenerator, name='rungenerator'),
@csrf_exempt Will allow you to bypass the token validation. Please check if your Ajax call is making the cross-origin error. if that the case you should either use cors-headers on your django app. btw using require_http_methods will force the function to check the HTTP method so you can be 100% sure all data that you will get will be POST
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.http import HttpResponse
@csrf_exempt
@require_http_methods(["POST"])
def rungenerator(request):
inputtype = request.POST.get('numberinput', None)
payload = {"response":str(inputtype)} if inputtype is not None else {"response":"please type something"}
return HttpResponse(json.dumps(payload, indent=2),
content_type='application/json',
status=200)