set referer url with ajax request

Gagan picture Gagan · Jan 10, 2012 · Viewed 30k times · Source

I want to set the referer page while sending an ajax request. I have done this way but it didn't work.

I have included this javascript in a local html file and the main url is cross domain.

$.ajax({
  url: "{{main url}}",
  dataType: "json",
  beforeSend: function(xhr){
  xhr.setRequestHeader('X-Alt-Referer', '{{referer url}}');
  },
  success: function(data){
    console.log(data);
  }
});

I got some hint from this url

Set a request header in JavaScript

I get

"NetworkError: 404 Not Found - {{main url}}"

error when i tried it from firefox console

What is wrong in this script or there is another way of doing this?

Answer

Serg picture Serg · Apr 17, 2013

try to use next code:

var main_url = "http://www.example1.com";
var referrer = "http://www.example2.com";
$.ajax({
  url: main_url,
  dataType: "json",
  headers: {'X-Alt-Referer': referrer },
  success: function(data){
    console.log(data);
  }
});