execute an ajax request without including any authentication headers

I am looking to create an ajax call with authorization headers only when the user enters a username and password. If these variables are empty, I need to create an ajax call without authorization headers. Is it possible to achieve this using just one ajax call, or do I need to create two separate ajax calls for each scenario?

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");
          }
      });

Answer №1

Consider the following solution:

let username = "user123";
let password = "pass123";

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

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

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

Answer №2

The object passed as a parameter to the $.ajax function holds all the necessary information for making an AJAX call. Simply define this object, add the required properties, and then pass it to the `$.ajax` function.

var ajaxParams = {
    type: "POST",
    url: api_endpoint,
    dataType: "json",
    success: 
      function (response) {
        console.log("Request successful");
    },
    error:
      function (error) {
        console.error("An error occurred");
    }
};

if(token){
    ajaxParams.headers = {
        'Authorization': "Bearer " + token
    };
}

$.ajax(ajaxParams);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to utilize a JSON file to input events into FullCalendar that can accommodate multiple users?

Here's how I'm integrating event information from my database with FullCalendar using PHP: Retrieve event information from the database. Organize the data into an array and customize formatting, colors, etc. Convert the array to JSON format usi ...

Flask Server produces a response with a considerable delay when accessed through AJAX

I am currently running 2 servers on localhost, each with different ports. One of them is a basic flask server in Python and its code is provided below: from flask import Flask,jsonify from flask_cors import CORS app = Flask(__name__) CORS(app) @app.rout ...

I am struggling to set up angular-localstorage4

I have been following the instructions in the provided link: angular-localstorage4 When attempting to import WebStorageModule and LocalStorageService from angular-localstorage, I encounter an error in the console even though the compilation is successful. ...

When a jQuery checkbox is checked, the addClass and toggleClass effects are applied to all DIVs, not just the enclosing DIV

I am working with Bootstrap Cards that have checkboxes inside them. When a checkbox is checked, I want to apply 2 specific classes to the Card DIVs: Change class="card border-secondary" to class="card border-success" Change class="card-header" to class ...

What is the best way to utilize mouseenter and mouseleave events concurrently?

I need some assistance with my website's star rating feature. When a user hovers over the stars, a popover should appear, and when they move their mouse away, the popover should disappear. Currently, I am using jQuery to achieve this functionality: $( ...

Concealing Bootstrap Dialog in Angular 6 through Component隐藏Angular 6中

I have been struggling to hide a bootstrap dialog from a component with no success. Here is my Dialog code: <div class="modal fade" id="loading_video_upload" tabindex="-1" role="dialog" aria-labelledby="loading_video_upload_label" aria-hidde ...

What is the best way to categorize quiz answers within an array?

Creating a five question quiz with four answers each was a challenging task. Now, I want to store each question/answer combination in its own position in an array. Here is a snippet of the HTML code I've written: <!DOCTYPE html> <html> &l ...

Modify components in a web application based on the content of a JavaScript variable

I'm in the process of developing a webapp that needs to interact with an Arduino for its inputs in order to dynamically change the contents of the webpage. Currently, I am experimenting with variables that I have created and assigned random numbers t ...

Transforming NIF to OBJ within the Blender 249.2 software results in an object that is not visible

I am currently utilizing Three.js for rendering Fallout 3 assets in WebGL. Check out the JavaScript code for a similar object rendering here. Most objects are loading fine along with their normals, except for the brahmin... While the texture and normals a ...

What are the steps to restrict a user from accessing a specific website?

In my Vue.js project, I've implemented a function that hides a specific menu item for users with insufficient permissions: <a :href="href" @click="navigate" v-if="hideMenuItem()"> // some code </a> hideMe ...

Executing two Ajax calls in ReactJS with different parameters can improve the efficiency of your

Why does the second Ajax call overwrite the first one, causing the results to be different each time I refresh it? In the first Ajax call, I have set tests: [], testsHistories: [] in the setState function. However, the second Ajax call only sets the stat ...

Unable to invoke setState (or forceUpdate) on a component that has been unmounted

After updating the component, I encountered an issue with fetching data from the server. It seems that componentWillUnmount is not helpful in my case since I don't need to destroy the component. Does anyone have a solution for this? And when should I ...

Utilizing numerous script elements for three.js library

Today, I ventured into the world of three.js for the first time, along with exploring html and js in general. While experimenting with some example code, I encountered an issue. It seems that importing the three.js file from the script tag in my Main.js ...

Error 400 encountered when trying to access National Weather Service data

Encountering a 400 error when making a simple NWS GET request for a point JSON dataset. The issue seems to be with the jQuery process, which is adding extra text after the longitude value in the URL - https://api.weather.gov/points/39.5,-105.5?_=16303483 ...

How to retrieve AJAX request variables in a Rails 3 controller

$("#shopname").keypress(function(){ $.ajax({ type: "POST", url: "/admin_home/test/", data: {email:$(this).val()} , success: $('#subcategory_details').append('<%=@sub1%> ') }); }); controller @sub1=params[:email] ajax request tri ...

Ways to stop two JavaScript files from running at the same time

After combining two JavaScript files, I am facing some issues. The first file handles validation while the second one has an ajax plugin for form submission after validation. When I include these files in the header section, they both run simultaneously. H ...

Stop Browsers from Saving the Current Page in the History Log

Currently, I am facing an issue with a user-triggered popup window on my website that redirects to another site. It is important that users do not access this page directly and only navigate to it if the popup window opens as intended. mysite.com -> my ...

What is the best way to update HTML content using JSF reRender or Ajax load, and then rebind the updated DOM with AngularJS?

Let's analyze the following piece of code: <div id="dest"> <p>Original Content</p> <p>Some data</p> <ul> <li ng-repeat="i in items">{{i.name}}</li> </ul> </div> Alternatively, u ...

Tips for bypassing the 304 not modified error in Rails4 and fixing issues with AJAX functionality

As a novice in the world of Rails, I am currently working on creating a basic application with it. However, I am encountering an issue where every time I refresh or reload a page, it returns a 304 not modified status and ajax functionality ceases to work ...

What is the best way to single out a specific item from a list to display in a component upon clicking in Vue.js?

To view the data of a specific item in the child component "comandasInd", I just need to click on the icon. <template> <v-data-table :items="comandas"> <template v-slot:items="props"> <td>{{ props.item.nombre }}</td& ...