76

I need to do a getJSON() request, but how do I pass authorisation and custom headers?

I am getting issues that the request header is taking the name, but NOT the values. The URL is being shown through a manual request in fiddler to being inserted in as options instead of GET/Url.

Here is an example of what we are trying to do that works fine in fiddler; how can I replicate this with the AJAX function?

GET /Service.svc/logins/gdd53535342/houses/vxcbdfsdg/people/dsgsdggd?format=json HTTP/1.1
User-Agent: Fiddler
Authorization: Basic rgbg423535fa23y4436
X-PartnerKey: df3fgeg-g5g6-b55b-f3d2-dsgg353523
Host: 154.34.53.54:2757

JavaScript code:

xhr = new XMLHttpRequest();

$(document).ready(function() {
  $.ajax({
    url: 'http://localhost:437/service.svc/logins/jeffrey/house/fas6347/devices?format=json',
    type: 'GET',
    datatype: 'json',
    success: function() { alert("Success"); },
    error: function() { alert('Failed!'); },
    beforeSend: setHeader       
  });   
});

function setHeader(xhr) {
  xhr.setRequestHeader('Authorization', 'Basic faskd52352rwfsdfs');
  xhr.setRequestHeader('X-PartnerKey', '3252352-sdgds-sdgd-dsgs-sgs332fs3f');
}

Fiddler Normal Request Headers:

GET /service.svc/logins/jeffrey/house/fas6347/devices?format=json HTTP/1.1
User-Agent: Fiddler
Authorization: Basic faskd52352rwfsdfs
X-PartnerKey: 3252352-sdgds-sdgd-dsgs-sgs332fs3f
Host: localhost:437

Fiddler Through Ajax() Request Headers:

OPTIONS service.svc/logins/jeffrey/house/fas6347/devices?format=json HTTP/1.1
Host: localhost:437
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Proxy-Connection: keep-alive
Origin: http://ipv4.fiddler:61975
Access-Control-Request-Method: GET
Access-Control-Request-Headers: authorization,x-partnerkey
APerson
  • 7,304
  • 5
  • 32
  • 48
Berty
  • 763
  • 1
  • 5
  • 5

3 Answers3

84

I agree with sunetos that you'll have to use the $.ajax function in order to pass request headers. In order to do that, you'll have to write a function for the beforeSend event handler, which is one of the $.ajax() options. Here's a quick sample on how to do that:

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        $.ajax({
          url: 'service.svc/Request',
          type: 'GET',
          dataType: 'json',
          success: function() { alert('hello!'); },
          error: function() { alert('boo!'); },
          beforeSend: setHeader
        });
      });

      function setHeader(xhr) {
        xhr.setRequestHeader('securityCode', 'Foo');
        xhr.setRequestHeader('passkey', 'Bar');
      }
    </script>
  </head>
  <body>
    <h1>Some Text</h1>
  </body>
</html>

If you run the code above and watch the traffic in a tool like Fiddler, you'll see two requests headers passed in:

  • securityCode with a value of Foo
  • passkey with a value of Bar

The setHeader function could also be inline in the $.ajax options, but I wanted to call it out.

Hope this helps!

superhero
  • 5,547
  • 9
  • 56
  • 88
David Hoerster
  • 27,332
  • 6
  • 63
  • 99
  • Please check changes made to the original post (New Question) – Berty Jul 13 '10 at 10:20
  • 2
    I'm not sure I understand the problem. The header key/values should be passed up to the service not as part of the URL, but as options (as you said). You would set X-PartnerKey and Authorization the way the example set 'securityCode' and 'passkey' (which were just headers I made up). Host and User-Agent should be set when you make the $.ajax call. Sorry if I'm not understanding the issue properly. If you have source code, please post it and maybe that will help. Thanks! – David Hoerster Jul 13 '10 at 12:51
  • 1
    I have set up the request headers the same way as you did for the examples, but after running this and viewing it through fiddler the names of the headers appear, but not the values. Also in fiddler i am trying to do a GET which would be displayed as GET/URL but if i set the type to GET it is appearing as OPTIONS/URL. Hope that makes more sense. I will post up source code but is virtually the same as yours. Thanks Again – Berty Jul 13 '10 at 14:21
  • Also is this compatible with IE and firefox? – Berty Jul 13 '10 at 14:26
  • Yes - there's nothing specific about the code that makes it tied to IE or FF. It should be compatible with any browser that supports XmlHttpRequest. I tested on IE8 & FF 3.5.10. – David Hoerster Jul 13 '10 at 15:17
  • You're getting the OPTIONS verb because you're probably requesting the service from a different origin than your site. If you're running through Fiddler, you're site's coming through ipv4.fiddler but you're requesting the service on localhost. My initial example may have been misleading - just request the '.svc' and service method - don't include the 'http://.../' part so that you're requesting the service from the same origin as your site. I updated my example accordingly. Sorry if that caused a problem. – David Hoerster Jul 13 '10 at 15:50
  • Sorry that was misleading i was trying both and getting the same affect, if i monitor the request through capture traffic in fiddler and use ipv4.fiddler, in internet explorer i get a 200 and the request comes back fine, if i use firefox i get a 405 error, the differences is that FF is passing it in as OPTIONS, and IE as a GET and that the values for the partnerkey and authentication are not there in FF but fine in IE. Got it working fine in IE but the same code won't work in FF any ideas? Thanks again for your help mate greatly appreciated. – Berty Jul 14 '10 at 09:54
  • Why the downvote, Mr. Anonymous Downvoter? If you downvote, you should state why. – David Hoerster Dec 14 '11 at 13:15
  • David can we send cookie value(sessionId) to remote protected page using your example by using anyorigion.com service?can you give in example on how to send cookie value using ajax to remote site? – user1788736 Jun 15 '13 at 07:09
  • 1
    These days you can define your headers in the `headers` property. – thdoan Jan 09 '19 at 03:26
39

I think you could set the headers and still use getJSON() like this:

$.ajaxSetup({
  headers : {
    'Authorization' : 'Basic faskd52352rwfsdfs',
    'X-PartnerKey' : '3252352-sdgds-sdgd-dsgs-sgs332fs3f'
  }
});
$.getJSON('http://localhost:437/service.svc/logins/jeffrey/house/fas6347/devices?format=json', function(json) { alert("Success"); }); 
Sean N.
  • 918
  • 2
  • 9
  • 21
  • 4
    From the docs (http://api.jquery.com/jquery.ajaxsetup/) : "Its use is not recommended." – matt burns Jul 01 '14 at 16:32
  • 5
    @matt-burns, true. My solution would cause every jquery ajax request to have those two values in the headers. I think in this case it is harmless. You would run into problems potentially if you were using ajaxSetup() to set the url or request type. That I would discourage. Something to be aware of. – Sean N. Jul 02 '14 at 15:30
  • 2
    In my case I actually have to use the same header for all getJSON calls, so this is a fine solution for me :) – marlar Feb 08 '17 at 11:22
15

The $.getJSON() method is shorthand that does not let you specify advanced options like that. To do that, you need to use the full $.ajax() method.

Notice in the documentation at http://api.jquery.com/jQuery.getJSON/:

This is a shorthand Ajax function, which is equivalent to:

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

So just use $.ajax() and provide all the extra parameters you need.

Manuel Jordan
  • 11,959
  • 15
  • 69
  • 111
sunetos
  • 3,288
  • 21
  • 14