3

How to set a custom Ajax request header with jQuery has an excellent answer here.

So, if I do

var headervar='testvalue';
$.ajax({
  type: "POST",
  url: "foo.php",
  headers:{'testname':headervar},
  ...
});

It nicely sets headers like

[Accept-Language] => en-US,en;q=0.5w-form-urlencoded;charset=UTF-8
[testname] => "testvalue"
[X-Requested-With] => XMLHttpRequest
...

However, I like to also set the header NAME. If it is hardcoded, like in the example above, it works OK. But if I do this with a variable

var headername='testname';
var headervar='testvalue';
$.ajax({
  type: "POST",
  url: "foo.php",
  headers:{headername:headervar},
  //...
});

The result is a header where the variablename suddenly becomes the headername.

[Accept-Language] => en-US,en;q=0.5w-form-urlencoded;charset=UTF-8
[headername] => "testvalue"

So the question: is it possible to set the headername as a variable in a jQuery Ajax request?

Community
  • 1
  • 1
Michel
  • 4,076
  • 4
  • 34
  • 52
  • 1
    The usual way to set custom headers to ensure that you are not conflicting with standards, is to use `x-myName`; in your case `x-testname`. (This is just a guideline not a requirement.) As you can allready see jQuery is setting the custom header `X-Requested-With: XMLHttpRequest` – Andreas Louv Mar 02 '15 at 14:09

1 Answers1

3

You need to create temporary object for that and use bracket notation to define object property name from variable:

var headername='testname';
var headervar='testvar';
var headers_to_set = {};
headers_to_set[ headername ] = headervar;
$.ajax({
  type: "POST",
  url: "foo.php",
  headers:header_to_set,
  //...
});
antyrat
  • 27,479
  • 9
  • 75
  • 76