2

I am trying to pass some data from the frontend to the backend of my site using AJAX. This is the post request view in my django views:

def post(self, request):
    id_ = request.GET.get('teacherID', None)
    print(id_)
    args = {}   
    return JsonResponse(args)

This is the function I have in javascript. I know the correct value is being passed because the console.log(teacher_id) prints the right value.

function send(teacher_id){
    console.log(teacher_id)
    var url = window.location.pathname;
      $.ajax({
        method: "POST",
        url: url,
        data: {
            'teacherID': teacher_id,
            },
        dataType: 'json',
        success: function (data) {
            //location.href = data.url;//<--Redirect on success
        }
        });
}

When the code is run, and the print statement in my view is run, regardless of what the teacher_id is, None is printed.

what is wrong with the code?

wtreston
  • 1,051
  • 12
  • 28
  • can you add contentType in your Ajax request - `contentType: "application/json;charset=utf-8",` , and try once. – Ejaz Dec 30 '17 at 09:58
  • 1
    You are retrieving the data using ```GET.get()``` while sending the request using ```method: "POST"```. My knowledge of Django isn't existent but language wise there's a mismatch there so I thought that might be it. Let me know if that's the issue so I can post an answer. – yarwest Dec 30 '17 at 09:59
  • 1
    @yarwest you were right, thanks for the help! Post the answer and Ill accept it – wtreston Dec 30 '17 at 10:01

1 Answers1

2

In your Django view the data is being retrieved using GET.get() while the AJAX request is sending it using method: "POST".

POST data can't be retrieved in the same way as GET data so you should either change the way the data is being send (by changing the method in the AJAX call to GET) or read it using the related POST methods.

You can visit this Stack Overflow question if you are doubting which method to use.

yarwest
  • 873
  • 8
  • 19