I'm trying to have Django to run a function when I tell it based off a JavaScript button. How do I accomplish this? Where do I write the Django function?
JavaScript in main.html:
function mainFunction(){
alert("Beginning API Main Function");
$.ajax({
type: 'POST',
url: 'livestream/postdata/',
success: function(){alert('DONE!');},
error:function(){alert('ERROR!');},
});
alert("ENDING API MAIN FUNCTION");
}
Urls.py:
url(r'^postdata$', 'livestream.views.postdata', name='postdata')
Views.py:
def postdata(request):
r = ...api... (I know that the api works)
print(r.text)
When I run the function 'mainFunction()' I get the two alerts and then another that says 'ERROR'. Why is this?
3 Answers 3
Set up a route in your urls.py file
url(r'^action/$', 'yourproject.views.action', name='action')
In your views.py file, you would create that action.
def action(request):
# do your magic!
Then, when someone interacts with that button, do an ajax call that hits the URL at /action.
1 Comment
You add a listener to the button which makes an ajax call when fired. In your view.py you handle the response for that ajax call.
1 Comment
@HieuNguyen
Thank You for answering my question. It was through chat, so I'll write down, what worked.
- in ajax need a '/' before lifestream. /livestream/postdata/
- url(r'^postdata/$', 'livestream.views.postdata', name='postdata')
in views.py
before function I needed @csrf_exempt
return HttpResponse(r)
url: '/livestream/postdata/',(notice that first/?)