HTTP_X_REQUESTED_WITH not set in ajax call with jquery
I am using Django to develop a new website and I am having a problem with an ajax request. I walked a lot and read a lot of posts and articles (most of them explain the same thing).
Problem: an ajax call is made and I got a request in the view, but request.is_ajax () returns false. For what I know, request.is_ajax () checks the value of the HTTP_X_REQUESTED_WITH header, but I can't see it in the request headers, so I can't check 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 opinion:
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 under 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 spent too much time with this (possibly stupid) error.
Thanks in advance.
source to share
I will answer my own question. The problem was the jquery.ajax () method. I don't know why, but this method does not set the X-Requested-With to the XMLHttpRequest, which Django needs to check if the request is an ajax request. I even tried to add a title in the manner prescribed in my previous comments ( headers: { 'X-Requested-With': 'XMLHttpRequest' }
and beforeSend: function(xhr) { xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); },
). Instead, I use the .get () method which I think sets this header by default and it works.
source to share