user14490044
user14490044

Reputation:

AJAX POST request error - `Uncaught TypeError: Illegal invocation`

If I try to do this, I get this error: Uncaught TypeError: Illegal invocation

$(document).on('input', '#search-inp', (e) => {
        $.ajax({
            type: 'POST',
            url: '/search/',
            dataType: 'json',
            data: {
                input: $('#search-inp').val(),
                csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]'),
            },
            success: function(data) {
                console.log(data);
            }
        });
    });

And if I try to do this, I get this error: 403: Forbidden

$(document).on('input', '#search-inp', (e) => {
        $.ajax({
            type: 'POST',
            url: '/search/',
            dataType: 'json',
            processData: false,
            contentType: false,
            data: {
                input: $('#search-inp').val(),
                csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]'),
            },
            success: function(data) {
                console.log(data);
            }
        });
    });
# This is my views.py
def search(request):
    return JsonResponse(data={
        'test': 'test'
    })

What could be the problem? Your help is greatly appreciated. Thank you

Upvotes: 0

Views: 151

Answers (1)

user14490044
user14490044

Reputation:

I am so sorry that I bothered everyone.

$(document).on('input', '#search-inp', (e) => {
        $.ajax({
            type: 'POST',
            url: '/search/',
            dataType: 'json',
            data: {
                input: $('#search-inp').val(),
                csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
            },
            success: function(data) {
                console.log(data);
            }
        });
    });

I had done this: csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]')

But should do this: csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()

Upvotes: 1

Related Questions