0

I'm trying to send a string to a post view via checkbox being checked and unchecked. The part I am having trouble with is on the post view being able to get read the data.

I have the name being generated during the templating of the HTML to tell me the id of the item. Then the javascript is supposed to pass the name of the checkbox to the post view and then just print out the post value.

Error

The error I'm getting is that it returned a "None" so I'm thinking I'm not getting the name right.

In the data field of the javascript, I also tried "data:{data:$header}" and I got the same result.

Javascript

$("input[type='checkbox']").change(function() {

      // console.log($header = $(this)[0].name)
      $header = $(this)[0].name

      $.post({
            url: "",
            data: $header,
            headers: {
                'X-CSRFToken': csrftoken
            }
        })

          });

Django view.py

class CurrentCodeView(LoginRequiredMixin,DetailView):
    template_name = 'codes/currentCodes.html'
    def get(self, request, *args, **kwargs):
     //doing alot of stuff

    def post(self,request,*args, **kwargs):
        print(request.POST.get('data'))
2
  • Suggest that you search StackOverflow for the phrase 'django csrfmiddlewaretoken ajax' (without the quotes) and you should find your answer among the many results. You need to send the data in the form: data = {csrfmiddlewaretoken: value of token } Commented Sep 24, 2018 at 19:21
  • Thank you for the suggestion, I did look that up, but It doesn't appear to have a problem with CSRF token. Before I added in the header It was giving me an error that specified the CSRF token, now its just returning a value of None which Is why I was thinking I was not calling something correctly in my post function Commented Sep 24, 2018 at 19:38

1 Answer 1

0

OK. You're not assigning a return value, and print doesn't return anything to the client. This will return a response to the client:

from django.http import JsonResponse

def post(self, request, *args, **kwargs):
    some_text = 'A reply'
    return JsonResponse({'some_text': some_text})
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I learned something new. So in order for the post request to be valid, it has to return something back? I can't just print the data sent.
Correct, and then you write Javascript code on the client side in order to access/use what you passed back. Look at the examples here: api.jquery.com/jquery.post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.