set referer url with ajax request

33k views Asked by At

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?

1

There are 1 answers

0
Serg On

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