Scope of the variable not defined within the ajax callback

function verifyDeleteFacilitator(facilitatorId, handleData) {
var request = $.ajax({
    type: 'GET',
    url: urls.verifydeletefacilitator,
    data:{facilitatorId: facilitatorId}
}).done(function (response) {
    return handleData(response);
})
}   

var deleteButtonText = "";
verifyDeleteFacilitator(facilitator.value, function (canBeDeleted) {
    console.log(canBeDeleted);
    if (canBeDeleted == true) {
        deleteButtonText = '<button class="badge btn-danger p-2" id="confirmDeleteFacilitator" type="button"><i class="fas fa-exclamation-triangle"></i>Confirm Deletion</button>';
    }

})

console.log(deleteButtonText);

The issue with canDeleteText not being set properly lies in the scope of the callback function. Here is how you could correct it:

Answer №1

You're not returning anything in your function .. It's important to set the var within the scope of the function unless you plan on passing it in as an argument ... For example:

canDeleteFacilitator(facilitator.value, function (canDelete) {
    var canDeleteText = "";
    console.log(canDelete);
    if (canDelete == true) {
        canDeleteText = '<button class="badge btn-danger p-2" id="deleteFacilitator" type="button"><i class="fas fa-exclamation-triangle"></i>Delete Permanently</button>';
    }
    return canDeleteText;
})

In simpler terms, keep canDeleteText within the function itself .. If you wish to use it outside the function, make sure to include a return statement at the end:

var canDeleteText = canDeleteFacilitator( callbacks );

To demonstrate this concept in action, define it as a function initially:

function canDeleteFacilitator(canDelete) {
    var canDeleteText = "";
    console.log(canDelete);
    if (canDelete == true) {
        canDeleteText = '<button class="badge btn-danger p-2" id="deleteFacilitator" type="button"><i class="fas fa-exclamation-triangle"></i>Delete Permanently</button>';
    }
    return canDeleteText;
}

var canDeleteText = canDeleteFacilitator(1); // Setting it to "true" to trigger the condition

console.log(canDeleteText);

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

Retrieving data from a MySQL query output

As a newcomer to PHP and MySQL development, I have created an application in Cordova using Visual Studio. The app functions as follows: The user chooses a serial number from a dropdown menu After selecting a serial number, the corresponding data is displ ...

Preventing Duplicate Submissions with the jQuery Form Plugin

While there are several discussions on this topic at SO, none seem to cover the amazing jQuery Form plugin that I heavily utilize in my application. I am looking to allow the user to only click 'submit' once and then disable the button until an ...

When transitioning to a different page, Angular is creating a duplicate of $scope

My webpage features a section where I showcase all the individuals stored in the database, referred to as the All Persons Page. Within this page, there are two primary options: Add New Person Delete Person (Any selected individual) An issue arises when ...

What are the essential Bootstrap CSS and JavaScript files that need to be connected to our HTML document?

I recently downloaded the most recent version of Bootstrap, which is version 4. Upon extraction, I noticed that it includes two folders: one for CSS and the other for JS. The CSS folder consists of approximately 12 CSS files, while the JS folder contains ...

Transferring data between nested IFrames and triggering a page refresh

Looking for a way to pass multiple values between two embedded IFRAMES and refresh the receiving iframe src. Is there any solution you recommend, specifically in c# code behind file (asp.net)? Welcome any ideas and suggestions. Thank you. ...

Exploring the Beauty of Cubes within Three.JS

Recently delving into the world of THREE.js, I've set out on a mission to create a cube composed entirely of cubes, much like this example: https://i.sstatic.net/hQRoB.jpg To achieve this, I've structured my 3D array as follows: [[grid][line,li ...

Enhancing Promises.all with extra parameters

Looking to dive into promises, eager to learn. Here is an array of shopIds I'm working with: let shopIdsArray = ['shop1','shop2','shop3']; Additionally, there's an external promise call: getProducts(shopId, ' ...

Incorporate this form created externally onto my website

I have been working on my website and I am looking to incorporate a form that opens up once the login button is clicked. This form was generated using an online form builder which provides an embed code for seamless integration onto websites. Below, you wi ...

"Utilizing the power of Node.js to perform SQL queries with

I'm having trouble with this SQL query that uses INNER JOIN. The query is returning an error. connection.query("SELECT caracavis.caracname FROM caracavis WHERE firstcaturl ='" + req.body[0].firstcatname + "' AND secondcaturl = '" + r ...

Difficulty maintaining root properties in AngularJS custom directive

I recently created a custom sidebar directive, and although it is loading correctly in the designated area, I am encountering issues with the dropdown functionality of certain tags. The desired behavior is for these tags to display their inner elements whe ...

Error on Node 101: The app.use function is throwing a ReferenceError because the [route]

I am still learning Node/Express and have a question about routing. I encountered an error message that says: app.use('/edu', edu); ^ ReferenceError: edu is not defined at Object.<anonymous> (/Users/ronitelman/Dropbox/happy ...

jQuery uploadify encountered an error: Uncaught TypeError - It is unable to read the property 'queueData' as it is undefined

Once used seamlessly, but now facing a challenge: https://i.stack.imgur.com/YG7Xq.png All connections are aligned with the provided documentation $("#file_upload").uploadify({ 'method' : 'post', 'but ...

Implementing an Audio Notification System in PHP

When a certain value is violated, I want to display multiple alert boxes as well as an audio alert. Additionally, I need an option to close the audio alert. My current attempt looks like this: if( ($mark<=$minValue) || ($mark>= $maxValue)) { ...

Revise a catalog when an object initiates its own removal

When rendering a card in a parent component for each user post, all data is passed down through props. Although the delete axios call works fine, I find myself having to manually refresh the page for updates to be displayed. Is there a way to have the UI ...

Difficulty updating Material UI table

Currently in the process of updating my react site to version 16.8, I have encountered an issue with a material ui table. The functionality involves users selecting certain options, triggering a rest call when a button is clicked, and then displaying the r ...

When the parent div overflows, the child div remains hidden within the boundaries of the parent div

<section class="margin-top-30"> <div class="row" style="position: relative;"> <div class="col-sm-4"> <div class="lightbgblock" style="overflow-x:visible;overflow-y:scroll;"> ...

Supporting server-side routing with NodeJS and Express for AngularJS applications

My current setup includes NodeJS + expressJS on the server and AngularJS on the client side. The routes defined in my AngularJS controller are as follows: app.config(function($routeProvider,$locationProvider) { $routeProvider .when('/field1/:id&apo ...

Creating fluid motion with a bezier curve in ThreeJS

I am looking to animate a bezier curve in ThreeJS with updating start, end, and control points. Eventually, I will have multiple curves animating simultaneously. What is the most efficient approach to achieve this? When running the code snippet below, you ...

Utilizing a JavaScript function to toggle the Bootstrap dropdown without the need for manual clicking

I've configured a Bootstrap dropdown in my site's mini cart that includes a lightbox effect to grey out the background content when the dropdown is activated. Here's the code snippet: $(".dropdown").on('show.bs.dropdown hide.bs.dropdow ...

Error occurs in React Native when trying to import routes due to type mismatch

My react native app is running on my physical device, but I encountered an error when importing routesContainer in my app.js. Can anyone shed some light on why this error is occurring? TypeError: Super expression must either be null or a function [Mon Oct ...