0

I want to create ajax call with authorization headears only when user writes username and password. When this vars are empty I need to create ajax call without authorization headers. How can I do this? Can I make it with one ajax or I need to create two ajax every for one situation?

var username = "user123";
var password = "pass123";

//var username = "";
//var password = "";    

$.ajax({
        type: "GET",
        url: url_survey,
        dataType: "json",
        headers: {
        'Authorization': "Basic " + btoa(username + ":" + password)
        },
        success: 
          function (data) {
            alert("SUCCESS");
       },
        error:
          function (data) {
            alert("ERROR");
          }
      });

2 Answers 2

2

Try this:

var username = "user123";
var password = "pass123";

//var username = "";
//var password = "";    
var headers = {}; //list of headers

if(username && password) //user and pass exists
    headers['Authorization'] = "Basic " + btoa(username + ":" + password);

$.ajax({
        type: "GET",
        url: url_survey,
        dataType: "json",
        headers: headers, //use our headers
        success: 
          function (data) {
            alert("SUCCESS");
       },
        error:
          function (data) {
            alert("ERROR");
          }
      });
1

The parameter passed to $.ajax is just an object. Just simply create it, add properties as needed, then send it to `$.ajax.

var ajaxData = {
    type: "GET",
    url: url_survey,
    dataType: "json",
    success: 
      function (data) {
        alert("SUCCESS");
   },
    error:
      function (data) {
        alert("ERROR");
      }
};

if(username  && password){
    ajaxData.headers = {
        'Authorization': "Basic " + btoa(username + ":" + password)
    };
}

$.ajax(ajaxData);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.