davidb
davidb

Reputation: 1603

Django ajax returning null

I'm using Django to handle a form that sends a post request to a view and ajax is supposed to return that without refreshing the page. Here's my Jquery with ajax:

$('.createFolder').on('submit', function(event){
  event.preventDefault();
  var folderName = $('#folderName').val();
  $.ajax({
    url: '{% url 'project:createFolder' %}',
    type: 'post',
    data: {
      'folderName': folderName,
      csrfmiddlewaretoken: '{{ csrf_token }}'
    },
    dataType: 'json',
    success: function(json) {
      alert(json);
    }
  });
});

Here's my view:

class createFolder(TemplateView):
template_name = "project/createFolder.html"

def post(self, request):
    folderName = request.GET.get('folderName')
    return JsonResponse(folderName, safe=False)

When running this the response I get displays "null". I'm not sure what is wrong here. Can anyone advise?

Thanks

Upvotes: 0

Views: 587

Answers (1)

Alasdair
Alasdair

Reputation: 309099

Since you are making a POST request, you should fetch the data from request.POST instead of request.GET.

folderName = request.POST.get(‘folderName’)

Upvotes: 1

Related Questions