16

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

Manu K Mohan
  • 823
  • 4
  • 9
  • 29
Dong
  • 911
  • 2
  • 9
  • 25
  • Does this answer your question? [X-Requested-With header not set in jquery ajaxForm plugin](https://stackoverflow.com/questions/1846675/x-requested-with-header-not-set-in-jquery-ajaxform-plugin) – Brian Tompsett - 汤莱恩 Jan 16 '22 at 19:03

6 Answers6

8

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");

Community
  • 1
  • 1
jitter
  • 53,475
  • 11
  • 111
  • 124
  • I was using jquery.load(url) method, I've also got this issue before with other methods. When this issue happened, I tried to trigger the event again and again and watch request info on firebug console panel, some of the request has no X-Requested-With header. But now when I trigger the event again, it doesn't happen. Thanks for your reply anyway, I'll keep an eye on it if it appears again next time. At least I can add param &ajax in request url to let backend recognize it. – Dong Dec 11 '09 at 13:11
  • Hi jitter, it happened again, I've provided more information in the question, could you please advise? – Dong Dec 14 '09 at 13:17
  • What jQuery version. What method (post, get)? What does the requested URL look like? – jitter Dec 15 '09 at 13:26
  • I've experienced this too using jQuery 1.6.2. It seems to happen when doing a $.post request but only after a page has been sitting idle for a few minutes. When this happens, Firebug confirms the request header lacks a X-Requested-With=XMLHttpRequest. Very odd.. – Levitikon Dec 20 '11 at 17:54
8

I was facing this issue as well with version 1.6.2, especially when the page has been setting idle for a while. Expanding on jitter's answer, this is adding the X-Requested-With redundantly for every request in one place. I put this in my Master page. Hope this works out.

$(document).ajaxSend(function (event, request, settings) {
    request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
});
Levitikon
  • 7,749
  • 9
  • 56
  • 74
  • Problem is without this header request is not assumed as ajax and therefore ajaxSend handler not being invoked – EvAlex Aug 29 '13 at 07:01
0

The reason I got this was because I was taking an element with my AJAX event handler attached, cloning it and then adding the new element to my document. For some reason this meant that the event attached to the new element would not treat it as a normal ajax request (Accept:text/html instead of application/json, no X-Requested-With etc.)

To fix this all I did was change the event to jQuery's new equivalent of live() (unsure what they call it now). So from:

$('a.basket-add').click(function() { /* etc */ });

To:

$(document).on('click', '.basket-add', function() { /* etc */ });
Hayley
  • 2,977
  • 3
  • 18
  • 16
0

I was just having the same problem myself, and I fixed it by ensuring there was a trailing slash after my url. So instead of:

$.get('/example/url')

use:

$.get('example/url/')

Looks like it's been a while since you posted this but maybe it will help!

lizlux
  • 586
  • 1
  • 8
  • 15
0

this may not be THE answer, but I was clawing my eyeballs out for a couple hours before figuring out that my mistake was pretty bone-headed. (What was killing me is that it was working on my dev box but not in production, and I still don't get why that is so, but...)

Make sure the event handler is really attached! If there's no X-Requested-With header it may be for good reason! I had a form whose action attribute was the correct url, and my submit button's "click" event was saying event.preventDefault() and then calling $.post(...), yadda yadda. Problem is, that DOM element was getting replaced as the result of some other xhr activity, and its event handler was getting blown away with it. The form was being submitted as a plain old POST, not ajax, hence no header.

So, rather than

$('#my-submit-button').on("click", data, function(event) {
    event.preventDefault();
    $.post(/* etc */);
})

it needed to be something like

$('#parent-div').on("click","#my-submit-button", function(event){
    event.preventDefault();
    $.post(/* etc */);
});

Further reading: https://learn.jquery.com/events/event-delegation/

David
  • 815
  • 8
  • 18
-1

Try this also by including the X-Requested-With as part of the Post values.

var postData = "X-Requested-With=XMLHttpRequest&" + $("#myFormId").serialize();
$.post(
    'http://www.mysite.com/blahblah',
    postData,
    function(data) { /*do whatever*/ },
    'html'
);

That and combine it with jitter's answer. Hope it helps!

EDIT NOTES:

I apologize I don't know what I was thinking. I must have misread the question when I posted.
This question is for Python django framework. Not for ASP.NET MVC.

I posted this answer because of the ASP.NET MVC's behavior based on the following source code.

ASP.NET MVC Source Code

Look at the AjaxRequestExtensions.cs class in the ASP.NET MVC source. http://aspnetwebstack.codeplex.com/SourceControl/changeset/view/60c2f18ed84838b1b3da671536a7a40033e67b0d#src/System.Web.Mvc/AjaxRequestExtensions.cs.

public static class AjaxRequestExtensions
{
  public static bool IsAjaxRequest(this HttpRequestBase request)
  {
      if (request == null)
      {
          throw new ArgumentNullException("request");
      }

      return (request["X-Requested-With"] == "XMLHttpRequest") ||
             ((request.Headers != null) && (request.Headers["X-Requested-With"] == "XMLHttpRequest"));
  }
}

MSDN Documentation on HttpRequestBase.Item Property

HttpRequestBase.Item Property
When overridden in a derived class, gets the specified object from the Cookies, Form, QueryString, or ServerVariables collections.

Therefore, request["X-Requested-With"] will look for that key in all the following places:

  • HTTP Form POST values
  • HTTP Cookie
  • HTTP Request Query String
  • and Server Variables.

So, if you include the X-Requested-With=XMLHttpRequest key-value pair as part of the HTTP POST like I am doing in the jQuery AJAX call, ASP.NET MVC will consider the HTTP Request as an AJAX HTTP Request.

Community
  • 1
  • 1
stun
  • 1,684
  • 3
  • 16
  • 25
  • 2
    This does not set an HTTP header. `X-Requested-With` is an HTTP header, not an `application/x-www-form-urlencoded` parameter. – Camilo Martin Feb 03 '13 at 21:43