0

I have an AJAX request to pull some data from post model"I am using Django3 and python 3.8". When I print the request.GET.get to the console, I got "None". There was no Data. However, when I alert the passed data in javascript I got the right value. I could not figure out which portion of my code should be tweak a little bit to work.

Here is the AJAX call:

   <script type="text/javascript">
   // to submit the get request and prevent the default submission
  $(document).on('click', '#post-det', function(e) {
    e.preventDefault();


    var post_id = $(this).children(':first-child').text();
    var post_id = parseInt(post_id);
    alert(post_id);

    $.ajax({
        'type':'GET',
        'url': "{% url 'get_post_details' %}",
        'data':post_id,
        'processData': false,
        'cache':false,
        'contentType': false,
        'dataType': 'json',
        csrfmiddlewaretoken:'{{ csrf_token }}',

        success: function(data) {

          alert(data)
        },

    });
    });  
   </script>

I got "2" for the post_ID

However, I could not retrieve it in Django view function. Here is the view function:

def post_details(request):
if request.method == 'GET' and request.is_ajax:


    post_id = request.GET.get('data')
    print("this is to check if the post_id is passed", post_id)
    print(request.GET.get)

    data = GetPostDetails(post_id)
    data = json.dumps(str(data))
    return JsonResponse(data, safe=False)
return JsonResponse({"error": "there was an error"}, status=status.HTTP_400_BAD_REQUEST)

The print function print this line.

this is to check if the post_id is passed None

<bound method MultiValueDict.get of <QueryDict: {'_': ['2345678976543']}>>
[04/May/2020 08:22:21] "GET /post/Post_details/?_=2345678976543 HTTP/1.1" 200 8

Also, this is the request header:

Request URL: // I removed it 
Request Method: GET
Status Code: 200 OK
Remote Address: 127.0.0.1:8000
Referrer Policy: no-referrer-when-downgrade
Response Headersview source
Content-Length: 8
Content-Type: application/json
Date: Mon, 04 May 2020 08:06:50 GMT
Server: WSGIServer/0.2 CPython/3.8.2
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Request Headersview source
Accept: application/json, text/javascript, */*; q=0.01
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Cookie: //I removed it//
Host: 127.0.0.1:8000
Referer: http://127.0.0.1:8000/ // I removed it 
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-origin
User-Agent: // I removed it 
X-Requested-With: XMLHttpRequest

NOTE: I did not have any error message but the json return empty object and when I hard coded the post_id and make it post_it = 1 . I have the object with all post details.
Your advice and guidance is highly appreciated.

2
  • What is the output of print(request.body)? Commented May 4, 2020 at 8:52
  • Here it is "[04/May/2020 08:54:09] "GET /post/Post_details/?_=2345678976544 HTTP/1.1" 200 8 Commented May 4, 2020 at 8:57

2 Answers 2

1
Try this as Igor Moraru suggest, using post:


# Python

def post_details(request):
    if request.method == 'POST' and request.is_ajax:

        post_id = request.POST.get('post_id')

        data = GetPostDetails(post_id)
        data = json.dumps(str(data))
        return JsonResponse(data, safe=False)




// Java script


$(document).on('click', '#post-det', function(e) {

    e.preventDefault();

    var post_id = $(this).children(':first-child').text();
    var post_id = parseInt(post_id);

    $.ajax({
          type: "POST",
          url: "{% url 'get_post_details' %}",
          dataType: "json",
          data: {
              "post_id": post_id
          },
          success: function(data) {
             console.log(data);
          }
      });

});

// Send the csrftoken
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

var csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for both of you Rodolfo and Igor. Your code is working. I think the problem was that csrf_token was not sent. I used your javascript code and it works with POST and GET method.
0

As you can see in your request there is not data passed to the api. You may want to use POST request to send data. GET method does not accept data parameter.

Comments

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.