Jquery, No X-Requested-With=XMLHttpRequest in ajax request header

jquery

SOME TIMES there is no X-Requested-With header, sometimes there is.

I checked in firebug and found that, don't know why.

So when I use request.is_ajax in django, it fails sometimes.

Anyone know how to fix it?


OK, now it happened again.
I opened the page and then left for supper for a long while, when I came back, it happened again. I recorded request header in firbugs:

Request with X-Requested-with:

Host localhost:8000
User-Agent Mozilla/5.0 (Windows; U; Windows
NT 5.2; zh-CN; rv:1.9.1.5) Gecko/20091102
Firefox/3.5.5
Accept text/html, /
Accept-Language zh-cn,zh;q=0.5
Accept-Encoding gzip,deflate
Accept-Charset GB2312,utf-8;q=0.7,*;q=0.7
Keep-Alive 300
Connection keep-alive
X-Requested-With XMLHttpRequest
Referer http://localhost:8000/gallery/
Cookie xxx

Request without X-Requested-with:

Host localhost:8000
User-Agent Mozilla/5.0 (Windows; U;
Windows NT 5.2; zh-CN; rv:1.9.1.5)
Gecko/20091102
Firefox/3.5.5
Accept text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8 Accept-Language zh-cn,zh;q=0.5 Accept-Encoding gzip,deflate
Accept-Charset GB2312,utf-8;q=0.7,*;q=0.7
Keep-Alive 300
Connection keep-alive
Referer http://localhost:8000/gallery/

Cookie xxx

Best Answer

Provide more information. What kind of ajax requests are you making?

If you are submitting forms which contain an input field of type file that is most likely the reason that the header is missing.

As you can't submit a file with ajax, all the javascript frameworks use the "hidden iframe" trick internally to get the work done for you.

Check this post with a similar problem and my answer to it.

X-Requested-With header not set in jquery ajaxForm plugin


Otherwise there should be no reason for such a behavior from jQuery as it always sets the header. If the issue isn't related to file-inputs please post relevant codesnippets

from jQuery Source

xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");