user3392045
user3392045

Reputation:

JQuery AJAX Header Authorization POST

I have to send XML to the server with Authorization header and it MUST be POST.

Now I have two options.

  1. When I use dataType = 'jsonp' it always becomes GET instead of POST. Also my data is must be XML.

            var request = {};
            request.type = 'POST';
            request.contentType = 'application/jsonp; charset=utf-8';
            request.dataType = 'jsonp';
            request.data = JSON.stringify(this.data);
            request.url = this.url;
            request.beforeSend = function (xhr) {
                xhr.setRequestHeader("Authorization", "Basic ");
            };
    
            request.processData = false;
            $.ajax(request);
    
  2. But without dataType = 'jsonp' I don't have Authentication header at all. The following code works only for Chrome.

        var request = {};
        request.type = 'POST';
        request.contentType = 'text/xml';
        request.dataType = 'xml';
        request.data = this.data;
        request.url = this.url;
        request.beforeSend = function (xhr) {
            xhr.setRequestHeader("Authorization", "Basic ");
        };
    
        request.processData = false;
        $.ajax(request);
    

Yes, I know that there are a lot of similar questions on StackOverflow and I've read dozens of them but still don't find the right answer.

Upvotes: 12

Views: 61903

Answers (1)

Gaurang s
Gaurang s

Reputation: 832

Modify headers in the beforeSend method, for example:

$.ajax({
    url: url,
    method: "POST",
    dataType: "json",
    crossDomain: true,
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify(data),
    cache: false,
    beforeSend: function (xhr) {
        /* Authorization header */
        xhr.setRequestHeader("Authorization", "Basic " + Utils.getUsernamePassword());
        xhr.setRequestHeader("X-Mobile", "false");
    },
    success: function (data) {

    },
    error: function (jqXHR, textStatus, errorThrown) {

    }
});

Upvotes: 18

Related Questions