Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP_X_REQUESTED_WITH not set in ajax call with jquery

I am using Django to develop a new website and I am facing a problem with an ajax request. I have been googling a lot and read a lot of posts and articles (most of them explain the same).

The issue: The ajax call is executed and I received the request in the view, but the request.is_ajax() returns false. For what I know the request.is_ajax() checks the value of the HTTP_X_REQUESTED_WITH header, but I can't see it in the request headers, thus I cannot check the is_ajax() in my view.

HTML form:

<form id="search-form" method="get" action="/search/">
    <input type="text" id="search" name="search" placeholder="Search">
    <button id="btn-search" >SEARCH</button>
</form>

Javascript:

$('#search-form').submit(function(e) {
    e.preventDefault();
    $.ajax({
        url : $('#search-form').attr('action'),
        type:'GET',
        data : {
            'search' : $('#search').val()
        },
        success: function(data, e) {
            alert("SUCCESS")
        },
        error: function(data) {
            alert("ERROR");
        },
    });
})

My view:

def search(request):
    if request.is_ajax():
        print "SOMETHING"
    if request.GET:
        import requests
        url = API_END_POINT + '&name=Bruce+Springsteen'
        response = requests.get(url).json()
        return HttpResponse(json.dumps(response), content_type='application/json')

    return render(request, 'core/search.html')

This is what I see in the Chrome Network tab:

General
    Remote Address:127.0.0.1:8000
    Request URL:http://localhost:8000/search/?search=Bruce+Springsteen
    Request Method:GET
    Status Code:200 OK
Response Headers
    Content-Type:application/json
    Date:Sat, 06 Jun 2015 10:18:51 GMT
    Server:WSGIServer/0.1 Python/2.7.6
    X-Frame-Options:SAMEORIGIN
Request Headers
    Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
    Accept-Encoding:gzip, deflate, sdch
    Accept-Language:es-ES,es;q=0.8,en;q=0.6
    Connection:keep-alive
    Cookie:djdt=hide; messages="73ba7b40cd0a4a7e0812a0350babd2d1dd268820$[[\"__json_message\"\0540\05425\054\"You have signed out.\"]]"; csrftoken=TXImtQ3inUdCCOLUbEvoU9Hc8ddqpUlV
    Host:localhost:8000
    Referer:http://localhost:8000/search/
    User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36
Query String Parameters
    search:Bruce Springsteen

Any ideas? I would appreciate any suggestions because I have spent too much time with this (probably silly) error.

Thank you in advance.

like image 599
pypy Avatar asked Feb 09 '23 22:02

pypy


1 Answers

I'm gonna answer my own question. The problem was with the jquery .ajax() method. I don't know why but this method does not set the X-Requested-With to XMLHttpRequest, which is needed by Django to check if the request is an ajax request. I even tried to add the header with the ways specified in my previous comment (headers: { 'X-Requested-With': 'XMLHttpRequest' } and beforeSend: function(xhr) { xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); },). Instead, I use the .get() method that I guess that by default set this header and it works.

like image 122
pypy Avatar answered Feb 20 '23 03:02

pypy