6

This is sort of a cross-domain issue, but the problem is the browser (Chrome) doesn't seem to follow the redirect. Instead, nothing is returned to the jQuery ajax call, and I get an error.

I'm trying to use jQuery.ajax, but the URL that I'm using redirects to another domain. When this happens, I get an error. Is there anything special that needs to be done so the browser will follow the redirect?

I already added access-control-allow-origin: * to the header of the second domain that is being redirected to.

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
Biagio Arobba
  • 1,075
  • 11
  • 27

2 Answers2

1

An HTTP redirect page is treated as any other HTTP page in that it also needs the access control headers. If your redirect page does not have them, the browser will never get around to checking if the page being redirected to has the proper permissions.

Along with the Location header on the redirect page, also add the Access-Control-Allow-Origin header and its related constituents (i.e. Access-Control-Allow-Methods etc.)

BigMacAttack
  • 4,479
  • 3
  • 30
  • 39
  • 2
    there is a lot of theory in your answer.. a couple of lines of code to illustrate what you're saying won't hurt – abbood Apr 22 '14 at 05:44
0

The only way to get a cross-domain ajax call is to use jsonp.

In jQuery, set your .ajax() dataType to 'jsonp'. See here: http://api.jquery.com/jQuery.ajax/

It still may not work, if the server being redirected to is not capable of a jsonp response. The difference between a json response and a jsonp response is that a json response is a pure json string, while a jsonp response is the code that calls a function passing in a json string.

A not-too-shabby tutorial: http://remysharp.com/2007/10/08/what-is-jsonp/

A good discussion: Can anyone explain what JSONP is, in layman terms?

Community
  • 1
  • 1
Jonathan M
  • 17,145
  • 9
  • 58
  • 91
  • 2
    cross domain ajax call is possible with Cross-Origin Resource Sharing (CORS) and author worked with this technology ( as he mentioned "access-control-allow-origin: *" header. ) – vadimk Sep 09 '12 at 22:13
  • @vadimk, Perhaps you can supply an answer involving this approach then. But it seems from the post that the problem is on the client-side. The `access-control-allow-origin` approach with CORS is on the server side. Even if the server allows it, the client wasn't allowing it. Thus JSONP. – Jonathan M Sep 11 '12 at 12:52
  • Jonathan, check out my answer. The solution involves making sure the redirect page has the proper response headers. – BigMacAttack Sep 14 '13 at 23:32