adamyonk
adamyonk

Reputation: 3175

$.ajax with auth silently failing in Safari (jQuery 2.1.3)

Anytime I try to send a $.ajax request (same origin) with username & password options in Safari, it just fails silently and never fires any complete, success, or error callbacks. The exact same request works fine in Chrome.

req = $.ajax
  url: ...
  type: 'POST'
  username: ...
  password: ...
  data: ...
req.done ...
req.fail ...

If I run the same code, but without username or password;

req = $.ajax
  url: ...
  type: 'POST'
  data: ...

The request actually goes through in Safari, but then obviously fails my server's auth. I'm not even really sure how to debug this. I tried dropping some log lines in jQuery's source around the $.ajax callback and it seems like the (attempted) authenticated request is never even going out in Safari.

UPDATED 1/8:

Also tested in Safari/Chrome with jQuery 1.11.0 and found the same results.

UPDATED 1/8:

gulty's beforeSend solution was the only way I could get basic auth to work in Safari:

req = $.ajax
  url: ...
  type: 'POST'
  beforeSend: (xhr) -> xhr.setRequestHeader('Authorization', 'Basic username:password')
  data: ...

Upvotes: 1

Views: 1368

Answers (1)

gulty
gulty

Reputation: 1076

Your code is fine for most browsers, anyway Safari isn't progressing the requests for reasons only the developers know.

There is a workaround - you need to set the request headers using headers: {} or within a beforeSend like so:

beforeSend: function (req) {
    req.setRequestHeader('Authorization', "username:password");
}

This is an addition to your code - you should still keep username: / password: for other browsers since I haven't properly tested the code without those credentials.

Upvotes: 2

Related Questions