4

What parameters on a $.ajax must I set to try and mask the AJAX-request as a normal request? I guess it has to do with the right headers.

I think a big part of the problem is that when working on a local .html-file, jQuery sets the header-value for Origin to null.

Is there any way to take out the Origin-header?

At this moment I'm getting different results from the same URL if I surf to it through the web-browser and when I do an jQuery AJAX-request.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Seb Nilsson
  • 26,200
  • 30
  • 103
  • 130

3 Answers3

7

Due to Same Origin Policy enforced by all modern browsers, this is not possible.

Seb Nilsson
  • 26,200
  • 30
  • 103
  • 130
6

The only thing that differs in an AJAX request sent with jQuery compared to a normal request (whatever you mean by normal request) is the X-Requested-With: XMLHttpRequest HTTP header that is added. This header could be removed like this:

$.ajax({
    url: '/foo',
    type: 'POST',
    data: { bar: 'baz' },
    beforeSend: function(xhr) {
        xhr.setRequestHeader(
            'X-Requested-With',
            {
                toString: function() { return ''; }
            }
        );
    },
    success: function(result) {
       alert(result);   
    }
});

or globally, for all AJAX requests on your site:

$.ajaxSetup({
    beforeSend: function(xhr) {
        xhr.setRequestHeader(
            'X-Requested-With',
            {
                toString: function() { return ''; }
            }
        );
    }
});
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Doesn't seem to work. I'm doing a GET if that makes any difference. – Seb Nilsson Jun 21 '11 at 21:46
  • @Seb Nilsson, no it doesn't make any difference whether you are doing GET or POST. In both cases the following code removes the `X-Requested-With` as shown in this live demo: http://jsfiddle.net/AUGQJ/1/ (inspect the request headers with FireBug and you won't find a trace of a `X-Requested-With`). – Darin Dimitrov Jun 21 '11 at 21:48
  • I didn't find it before either. But I still think that Origin is set to null is a problem. – Seb Nilsson Jun 21 '11 at 21:56
  • 3
    This does NOT remove the header, it merely sets its value to an empty string. The header is still sent. – Nicholas Shanks Feb 21 '13 at 09:40
  • This is wrong. An XML-Http-Request also sends an origin header. –  Aug 26 '16 at 20:53
1
  1. jQuery doesn't set Origin Header. Only browser itself can do it. And jQuery(or javascript) has no power over this header.

  2. here is a link about Origin Header cases set to null Null Origin Header

  3. the only difference between jquery and regular request is indeed X-Requested-With: XMLHttpRequest you can remove it by hand or you can make requests with new XMLHttpRequest, or with fetch().

good luck

Mihey Mik
  • 1,643
  • 13
  • 18