Is there a way to ensure an ajax call finishes executing without relying on 'async: false' or callbacks?

In my view, I have implemented a TypeScript code defining a KnockoutJS binding handler for a clickable element as shown below:

module MyModule {
    export interface ICopyButtonParams {
        dataUrl: string;
    }

    ko.bindingHandlers.copyButton = {
        init: (element: HTMLElement, valueAccessor: () => ICopyButtonParams) => {
            var options: any = ko.utils.unwrapObservable(valueAccessor());
            if (!options.dataUrl) {
                return;
            }

            new Clipboard(element, {
                text: () => {
                    var clipboardData: string;

                    $.ajax({
                        url: options.dataUrl,
                        type: "GET",
                        contentType: "application/json",
                        cache: false,
                        async: false,
                        success: (result: SubmitResult) => {
                            clipboardData = result.Data;
                        }
                    });

                    return clipboardData;
                }
            });
        }
    };
}

The purpose of this binding handler is to enable the clickable element with Clipboard.JS, which allows storing a string in the clipboard upon clicking. In my scenario, I intend to utilize Clipboard.JS's dynamic text feature, where you provide a function that returns the desired clipboard content. Within this function, there is an AJAX call made to an API for fetching the text to be stored.

Due to the architecture constraints, using a standard asynchronous AJAX call with a success callback is not feasible as it may not resolve the clipboard text in time.

To address this issue, I have temporarily resorted to executing my AJAX call asynchronously (not ideal). Since the 'async' flag in JQuery has been deprecated from version 1.8 onwards, I am exploring alternative solutions.

Any suggestions on how to tackle this challenge?

Answer №1

Handling the click event on your own might be a more effective approach.

After your AJAX callback, you can create a textarea, set its value, select it, and then use document.execCommand('copy'), similar to how Clipboard.JS functions (apologies for using JavaScript instead of TypeScript).

ko.bindingHandlers.copyButton = {
  init: function(element, valueAccessor) {
    var url = ko.utils.unwrapObservable(valueAccessor());

    $(element).click(function() {
      $.ajax({
        url: url,
        type: "GET",
        contentType: "application/json",
        cache: false,
        async: false,
        success: function(result) {
          var ta = document.createElement('textarea');
          document.body.appendChild(ta);
          ta.value = result;
          ta.select();
          var r = document.createRange();
          r.selectNode(ta);
          document.getSelection().addRange(r);
          document.execCommand('copy');
          document.body.removeChild(ta);
        }
      });
    });
  }
};

You can check out a similar working example here (without an AJAX request)

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

To effectively manage the form, I must carefully monitor any modifications and update the SAVE button accordingly in an Angular application

Are you experiencing an issue with detecting any changes on a page, where there is some information displayed and even if no changes are present, the SAVE button remains active for clicking? ngOnInit(): void { this.createConfigForm() th ...

Include the HTTP header in a GET request for an HTML hyperlink

Within my HTML code, I am using an <a> tag that will trigger a 302 redirect when clicked. However, I need to incorporate some HTTP headers into this GET request. Is there a way to achieve this without including the headers in the href attribute? Tha ...

Vue.js is unable to recognize this type when used with TypeScript

In my code snippet, I am trying to set a new value for this.msg but it results in an error saying Type '"asdasd"' is not assignable to type 'Function'. This issue persists both in Visual Studio and during webpack build. It seems like Ty ...

JavaScript Class Emit Signal for establishing a sequence of interconnected events

My Vue project includes a JavaScript class specifically for mobile devices. I'm looking to have this class emit a signal once the property 'hasEnded' is set to True for my object. How can I achieve this and chain together other events based ...

Change a nested for-loop into an Observable that has been transformed using RxJS

Currently, the following function is operational, but I consider it a temporary solution as I'm extracting .value from a BehaviorSubject instead of maintaining it as an observable. Existing Code Snippet get ActiveBikeFilters(): any { const upd ...

Designing personalized plugins with Typescript in Nuxt

In my Nuxt project, I have implemented a custom plugin file that contains an object with settings called /helpers/settings: export const settings = { baseURL: 'https://my-site.com', ... }; This file is then imported and registered in /plugi ...

Issue with ng2-charts not rendering properly on the client side when utilized in Angular version 2.0.0-beta-17

Struggling with using ng2-charts in my Angular 2 app and encountering some challenges. app.ts import {Component} from 'angular2/core'; import {CHART_DIRECTIVES} from 'ng2-charts/ng2-charts'; @Component({ selector: & ...

Display an error popup if a server issue occurs

I'm considering implementing an Error modal to be displayed in case of a server error upon submitting a panel. I'm contemplating whether the appropriate approach would be within the catch statement? The basic code snippet I currently have is: u ...

I've added a check, so why is TypeScript still complaining about the possibility of my property being undefined?

const handleLinkClick = (index: number) => () => { const hasUrl = !!searchItems[index]?.url; if (hasUrl) { navigateToLink(searchItems[index]?.url); } else { setItemSelected(index); } }; However, the issue I encountered is: (property) ...

Angular - Evaluating the differences between the object model and the original model value within the view

To enable a button only when the values of the 'invoice' model differ from those of the initial model, 'initModel', I am trying to detect changes in the properties of the 'invoice' model. This comparison needs to happen in th ...

Optimal method for submitting AJAX data through a form and retrieving the response value

I have a small form that needs to dynamically update values in select boxes using jQuery on change events. Here is the code snippet: $("form#updateclient select").change(function(){ // use one selector for all 3 selects $.post("inc/process-update.php" ...

Integrating Gatsby.js with my Express server for seamless communication

Currently, I am in the process of developing a basic full-stack application that utilizes Gatsby for the front-end and a simple Express server for the backend. Within my database, there are several users, and my objective is to fetch these users from the b ...

Executing AJAX function via a dropdown button

Utilizing a jquery-based dropdown menu from here. The dropdown is added to an existing button triggering an AJAX call that removes a row from the screen. The goal is to execute the AJAX call when any option in the dropdown is selected, instead of using th ...

Mastering Angular Apollo Error Resolution Methods

Hey everyone, I'm facing a problem with apollo-angular and apollo-link-error that I just can't seem to figure out. I've experimented with different approaches but have had no luck catching errors on the client-side of my angular web app. Bel ...

Tips for utilizing AJAX to send two values to PHP for comparison

How can I use AJAX to compare two values (#cpassword and #password) to see if they match? I've been attempting it, but it seems like I only get the value of '#cpassword'. Here is my cpassword-check.js file: // Validate confirm password whi ...

The readyState of Ajax is consistently anything but 4

I have encountered an issue with my JavaScript code. I am running these codes in order to display data based on user input. Despite there being no error connection and the connection happening properly, whenever I enter a name it always goes into the else ...

Encountering TS 2732 error while attempting to incorporate JSON into Typescript

Having trouble importing a JSON file into my TypeScript program, I keep getting error TS2732: Can't find module. The JSON file I'm trying to import is located in the src folder alongside the main.ts file. Here's my code: import logs = requi ...

Can Envs in Bit be linked together?

My React environment is set up at this link: . It is configured with the following dependencies: { /** * standardize your component dependencies. * @see https://bit.dev/docs/react-env/dependencies **/ "policy": { // peer and dev ...

Guide on incorporating a bespoke cordova plugin into your Ionic 4 project

After successfully completing all the necessary steps to create a new Cordova plugin as outlined in the link below: Start android activity from cordova plugin I executed the command cordova plugin ls which returned the following result: com.example.sam ...

The MySQL query is returning a blank result with only the column headings displaying

I have been working on improving my skills in PHP and AJAX by developing an application that enables users to search a database for real-time product stock information. Currently, I am facing an issue where the headings are displayed when a user types a le ...