Reputation: 1061
So I am using the same view in Django to do two things, depending on if the request is a GET or a POST method.
The GET method is simply to render the page when the user requests it, and the POST is when I use ajax to send information from the frontend, to the view so that i can process it and save it in the database.
Here is the Javascript/Ajax:
var url = window.location.pathname;
$.ajax({
url: url,
data: {
'vals': vals
},
dataType: 'json',
success: function (data) {
//On sunccess
}
});
The window.location.pathname contains the review_id in it and looks like:
/reviews/*ID*/add_questions/
This is my Django View:
def add_questions(request, review_id = None):
#print('yes')
if request.method == 'GET':
try:
review = ReviewBlock.objects.get(pk = review_id)
args = {'review': review}
return render(request, 'add_questions.html', args)
except ObjectDoesNotExist:
return HttpResponseNotFound('<h1>Page not found</h1>')
elif request.method == 'POST':
print(review_id)
As you can see, I have a print statement to see if the ajax call is working, however, it never prints it in the console.
Upvotes: 1
Views: 423
Reputation: 309049
$.ajax
defaults to GET requests. To do a POST request, you either need to add type: "POST",
$.ajax({
type: "POST",
url: url,
...
or use the $.post
shortcut
$.post({
url: url,
...
If you use the same request method for ajax and non-ajax requests, you may find the request.is_ajax()
method useful
Upvotes: 3